题目描述
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.
Example1:
Input: "3+2*2" Output: 7
Example2:
Input: " 3/2 " Output: 1
Example3:
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.
解题思路
- 可以举一个例子 2 + 3 * 4 + 5
- 我们先将符号预设为 ‘+’
- isdigit,isspace 都是内置,可以传一个char来进行判断
class Solution {
public:
int calculate(string s) {
stack<int> s_num;
int res = 0;
long long int tmp = 0;
char sign = '+'; // sign记录本次数字之前的上一个运算符,初始值为'+'
for(int i = 0; i < s.size(); i++){
if(isdigit(s[i])){ // 这里的函数是内置的
tmp = tmp * 10 + s[i] - '0';
}
if(!isdigit(s[i]) && !isspace(s[i]) || i == s.size() - 1){ // 最后一步需要进行1次计算
if(sign == '-'){ // 这里保存的其实是前一个操作符
s_num.push(-tmp);
}else if(sign == '+'){
s_num.push(tmp);
}else{
int num;
if(sign == '*'){
num = s_num.top() * tmp;
}else{
num = s_num.top() / tmp;
}
s_num.pop();
s_num.push(num);
}
sign = s[i];
tmp = 0;
}
}
while(!s_num.empty()){
res += s_num.top();
s_num.pop();
}
return res;
}
};