LeetCode 227. Basic Calculator II
阿新 • • 發佈:2018-12-28
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.
經典題啊啊
用兩個棧分別存數字和運算子
atoi是c的函式,輸入不能是string,需要是char陣列,所以需要對string使用.c_str()變為char陣列(指標)
class Solution
{
public:
int calculate(string s)
{
if (s.size() == 0)
return 0;
int res = 0;
stack<int> stk;
int num = 0;
char lastop = '+';
for (int i = 0; i < s.size(); i++)
{
if (s[i] >= '0' && s[i] <= '9')
{
num *= 10;
num += s[i] - '0';
}
if ((s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/') || i == s.size() - 1)
{
if (lastop == '+')
stk.push(num);
if (lastop == '-')
stk.push(-num);
if (lastop == '*')
{
int topnum = stk.top();
stk.pop();
stk.push(num * topnum);
}
if (lastop == '/')
{
int topnum = stk.top();
stk.pop();
stk.push(topnum / num);
}
lastop = s[i];
num = 0;
}
}
while (!stk.empty())
{
int topnum = stk.top();
res += topnum;
stk.pop();
}
return res;
}
};