LeetCode-Basic Calculator II-解题报告

原题链接https://leetcode.com/problems/basic-calculator-ii/

Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, +, -, *, / operators and empty spaces. The integer division should truncate toward zero.

You may assume that the given expression is always valid.

Some examples:

 

"3+2*2" = 7
" 3/2 " = 1
" 3+5 / 2 " = 5

 

解题报告:

由于只有加减乘除,和空格符号没有括号之类的东西,所以可以使用栈数据结构,将数字和运算符压入栈中,当遇到的符号式乘号或者除号的时候

将栈顶弹出,并在读入一个操作数,将其运算后,在压入栈中。

最后栈中剩下的只是一些加减法。可以将其全部转换成加法的情况,例如1-2可以表示成1+(-2),方便code

class Solution {
public:
    int calculate(string s) {
		if (s.length() == 0)return 0;
		stack<int>Stack;
		int op1, op2, i = 0, ans = 0;
		string str = "";
		for (i = 0; i < s.length(); ++i)if (s[i] != ' ')str += s[i];
		s = str;
		i = 0;
		op1 = stoi(s, i);
		Stack.push(op1);
		for (; i < s.length();)
		{
			char type = s[i];
			i++;
			int op2 = stoi(s, i);
			if (type == '*')
			{
				op1 = Stack.top();
				Stack.pop();
				Stack.push(op1 * op2);
			}
			if (type == '/')
			{
				op1 = Stack.top();
				Stack.pop();
				Stack.push(op1 / op2);
			}
			if (type == '+')
			{
				Stack.push(-1);
				Stack.push(op2);
			}
			if (type == '-')
			{
				Stack.push(-2);
				Stack.push(op2);
			}
		}
		
		while (!Stack.empty())
		{
			op2 = -1;
			op1 = Stack.top();
			Stack.pop();
			if (!Stack.empty())
			{
				op2 = Stack.top();
				Stack.pop();
			}
			if (op2 == -1)ans += op1;
			if (op2 == -2)ans += (-op1);
		}
		return ans;
	}
	int stoi(string& s, int& pos)
	{
		int tmp = 0;
		while (s[pos] >= '0' && s[pos] <= '9' && pos < s.length())
		{
			tmp = tmp * 10 + (s[pos] - '0');
			pos++;
		}
		return tmp;
	}
};


 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值