您的位置:首页 > 其它

227. Basic Calculator II

2016-06-27 15:39 281 查看
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


Note: Do not use the 
eval
 built-in
library function.
题意:实现简单的运算器,处理整数的加减乘除操作。
思路:用数字栈和符号栈进行运算操作。

class Solution {
public:
int calculate(string s) {
stack<int> numStack;
stack<char> operatorStack;
int p1 = 0;
int p2 = 0;
const int size = s.size();
while (p2 < size){
if (s[p2] == '+' || s[p2] == '-' || s[p2] == '*' || s[p2] == '/'){
numStack.push(stringToInt(s.substr(p1, p2 - p1)));
if (operatorStack.empty()){
operatorStack.push(s[p2]);
}
else{
switch (s[p2]){
int a;
int b;
int c;
case '+':
case '-':
while (!operatorStack.empty()){
b = numStack.top();
numStack.pop();
a = numStack.top();
numStack.pop();
char ch = operatorStack.top();
operatorStack.pop();
if (ch == '+')
c = a + b;
else if (ch == '-')
c = a - b;
else if (ch == '*')
c = a*b;
else
c = a / b;
numStack.push(c);
}

operatorStack.push(s[p2]);
break;
case '*':
case '/':
char ch = operatorStack.top();
if (ch == '+' || ch == '-'){
operatorStack.push(s[p2]);
break;
}
else{
b = numStack.top();
numStack.pop();
a = numStack.top();
numStack.pop();

operatorStack.pop();
if (ch == '*')
c = a*b;
if (ch == '/')
c = a / b;
numStack.push(c);
operatorStack.push(s[p2]);
break;
}
}
}
p2++;
p1 = p2;
}
else{
p2++;
}
}

numStack.push(stringToInt(s.substr(p1, p2 - p1)));
while (!operatorStack.empty()){
int b = numStack.top();
numStack.pop();
int a = numStack.top();
numStack.pop();
char ch = operatorStack.top();
operatorStack.pop();
int c;
switch (ch){
case '+':
c = a + b;
break;
case '-':
c = a - b;
break;
case '*':
c = a * b;
break;
case '/':
c = a / b;
break;
}
numStack.push(c);
}
return numStack.top();
}
private:
int stringToInt(string s){
int a;
stringstream ss;
ss << s;
ss >> a;
return a;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: