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.遇到*或者/,表示这个数要与后面的数进行乘或者除
class Solution {
public:
int calculate(string s) {
int sign = 1, i = 0, num = getNextNum(s, i), res = 0;
while(i < (int)s.size()){
if(s[i] == '+'){
res += num*sign;
sign = 1;
num = getNextNum(s, ++i);
}else if(s[i] == '-'){
res += num*sign;
sign = -1;
num = getNextNum(s, ++i);
}else if(s[i] == '*'){
num *= getNextNum(s, ++i);
}else{
num /= getNextNum(s, ++i);
}
}
res += num*sign;
return res;
}
private:
int getNextNum(string &s, int &i){
int next = 0;
while(i < (int)s.size()){
if(isdigit(s[i])){
next = next*10 + s[i] - '0';
}else if(s[i] != ' '){
return next;
}
++i;
}
return next;
}
};
class Solution {
public:
int calculate(string s) {
istringstream in('+' + s + '+');
long long total = 0, term = 0, n;
char op;
while (in >> op) {
if (op == '+' or op == '-') {
total += term;
in >> term;
term *= op == '+' ? 1 : -1;
} else {
in >> n;
if (op == '*')
term *= n;
else
term /= n;
}
}
return total;
}
};