免去了用栈的方法。
class Solution {
public:
int calculate(string s) {
long res = 0, tmp = 0, curNum = 0, n = s.size();
//res存结果,tmp存当前高优先级运算结果,curNum存当前字母段所代表的数值
char op = '+';
for (int i = 0; i < n; i ++ )
{
char c = s[i];
if (isdigit(c)) curNum = curNum * 10 + c - '0';
if (c == '+' || c == '-' || c == '*' || c == '/' || i == n - 1)
{
switch(op)
{
case '+' : tmp += curNum; break;
case '-' : tmp -= curNum; break;
case '*' : tmp *= curNum; break;
case '/' : tmp /= curNum; break;
}
//单独判断连乘、连除结束 或 达到最后一个字符,例如:3 + 2 * 2
//如果没有下面这个if则会变成(3 + 2) * 2
if (c == '+' || c == '-' || i == n - 1)
{
res += tmp;
tmp = 0;
}
op = c; //更新操作符
curNum = 0;
}
}
return res;
}
};