题目链接:https://leetcode.com/problems/basic-calculator-ii/#/description
题目描述:
mplement 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.
代码1:
class Solution {
public:
int calculate(string s) {
if(s.length()==1)
return s[0]-'0';
stack<char> opr;
stack<int> num;
for(int i=0;i<s.length();i++)
{
if(s[i]>='0'&&s[i]<='9')
{
int tmp=s[i]-'0';
i++;
while(i<s.length()&&s[i]>='0'&&s[i]<='9')
{
tmp=tmp*10+s[i]-'0';
i++;
}
i--;
num.push(tmp);
}
else if(s[i]==' ')
continue;
else
{
if(s[i]=='*'||s[i]=='/')
{
if(!opr.empty()&&(opr.top()=='*'||opr.top()=='/'))
{
while(!opr.empty())
{
if(opr.top()=='*'||opr.top()=='/')
{
calc(num,opr);
}
}
opr.push(s[i]);
}
else
opr.push(s[i]);
}
else
{
while(!opr.empty())
{
calc(num,opr);
}
opr.push(s[i]);
}
}
}
while(!opr.empty())
calc(num,opr);
return num.top();
}
void calc(stack<int> &num, stack<char>& oper )
{
int tmp1=num.top();
num.pop();
int tmp2=num.top();
num.pop();
if(oper.top()=='+')
{
num.push(tmp2+tmp1);
oper.pop();
}
else if(oper.top()=='-')
{
num.push(tmp2-tmp1);
oper.pop();
}
else if(oper.top()=='*')
{
num.push(tmp2*tmp1);
oper.pop();
}
else
{
num.push(int(tmp2/tmp1));
oper.pop();
}
}
};
后来搜答案,看到一个思路最简洁,代码罪简洁的http://blog.csdn.net/summer_liuwei/article/details/49383785,参考着重新写了一下,思路就是先计算乘除和减法,将每步结果压入栈中,最后再加起来
代码2:
class Solution {
public:
int calculate(string s) {
//先计算乘除,减当用加来计算,最后计算加
stack<int> num_stack;//存放数字,慢一步
int num = 0;//当前数字
char sign = '+';
for (int i = 0; i<s.length(); i++)
{
if (s[i] >= '0'&&s[i] <= '9')
{
num = num * 10 + s[i] - '0';
}
if (s[i] == ' '&&i!=s.length()-1)
continue;
if (s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/'||i==s.length()-1)
{
switch (sign)
{
case '+':
break;
case '-':
num = -num;
break;
case '*':
num = num_stack.top()*num;
num_stack.pop();
break;
case '/':
num = num_stack.top() / num;
num_stack.pop();
break;
default:
break;
}
num_stack.push(num);
sign = s[i];
num = 0;
}
}
//加起来
while (!num_stack.empty())
{
num += num_stack.top();
num_stack.pop();
}
return num;
}
};