原题链接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;
}
};