227. Basic Calculator II
- 只涉及 = - x / 以及含有空格
class Solution {
public:
int calculate(string s) {
stack<int> stk;
char sign = '+';
int num = 0;
for(int i=0; i<s.size(); i++){
char c = s[i];
if(isdigit(c)){
num = num*10+(c-'0');
}
if((!isdigit(c) && c!=' ' ) || i==s.size()-1){
switch (sign){
int tmp;
case '+':
stk.push(num);break;
case '-':
stk.push(-num);break;
case '*':kk
tmp = stk.top();
stk.pop();
stk.push(tmp*num);break;
case '/':
tmp = stk.top();
stk.pop();
stk.push(tmp/num);break;
}
sign = c;
num = 0;
}
}
int res=0;
while(!stk.empty()){
res+=stk.top();
stk.pop();
}
return res;
}
};
772. Basic Calculator
class Solution {
public:
int calculate(string s) {
return helper(s);
}
private:
string str;
int helper(string &s){
stack<int> stk;
char sign = '+';
int num = 0;
while (!s.empty()){
char c = s[0];
s = s.substr(1);
if(isdigit(c)){
num = num*10+(c-'0');
}
if(c == '(')
num = helper(s);
if((!isdigit(c) && c!=' ' ) || s.size()==0){
switch (sign){
int tmp;
case '+':
stk.push(num);break;
case '-':
stk.push(-num);break;
//case '*':
// tmp = stk.top();
// stk.pop();
// stk.push(tmp*num);break;
//case '/':
// tmp = stk.top();
// stk.pop();
// stk.push(tmp/num);break;
}
sign = c;
num = 0;
}
if(c==')') break;
}
int res=0;
while(!stk.empty()){
res+=stk.top();
stk.pop();
}
return res;
}
};