题目:
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.
Example 1:
Input: "3+2*2" Output: 7
Example 2:
Input: " 3/2 " Output: 1
Example 3:
Input: " 3+5 / 2 " Output: 5
Note:
- You may assume that the given expression is always valid.
- Do not use the
eval
built-in library function.
思路:
这题是224的延申,同样也是用stack存数字,虽然看上去增加了乘和除,难了一点,但是它去掉了括号,因此medium难度。首先用stack存数字,这里存的是在符号前已经被操作完的数字,比如"3+2*2",遇到‘+’时,存的是{3},然后遇到‘+’时,存的是{3,2}。对于数字的处理,和以前一样,用一个int cur保存当前数字,每次遇到数字就乘十进位再加上遇到的数字。这里还会遇到空格,不过只要直接跳过即可。然后剩下的就是符号了,加减乘除,每次遇到符号,我们先处理手中的符号sign和数字cur。如果手里的sign是‘+’, 那么直接cur塞进stack,如果是‘-’,取相反数再塞进stack,因为里面存的是已经处理完的数字,我们最后的结果是整个stack的和(相当于把整个string看成多个小部分,那么负数只要取正数的反即可),‘*’则把当前数字乘以栈顶数字,‘/’同样的,栈顶数字除以当前数字。之后更新当前数字和当前符号,数字置为0,符号依据目前读到的符号即可。最后一小段的话出了循环还是要处理一下手中的符号和数字,这一段写的有点难看,理论上可以直接放入循环内的,比如当i==s.size()-1的时候,进行运算等等,不过不影响结果,就是这种可以改造的重复确实很丑。最后的最后把stack中的所有数相加即是结果。
代码:
class Solution {
public:
int calculate(string s) {
stack<int> nums;
int cur=0;
char sign='+';
for(auto c:s)
{
if(isdigit(c))
cur=cur*10+(c-'0');
else if(c==' ')
continue;
else
{
if(sign=='+')
nums.push(cur);
else if(sign=='-')
nums.push(-cur);
else if(sign=='*')
nums.top()=nums.top()*cur;
else if(sign=='/')
nums.top()=nums.top()/cur;
sign=c;
cur=0;
}
}
if(sign=='+')
nums.push(cur);
else if(sign=='-')
nums.push(-cur);
else if(sign=='*')
nums.top()=nums.top()*cur;
else if(sign=='/')
nums.top()=nums.top()/cur;
int ans=0;
while(nums.size())
{
ans+=nums.top();
nums.pop();
}
return ans;
}
};