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:,唯一的差别就是本题少了括号,多了*和/,这就要求在做运算前必须先判断优先级。不多说,代码类似于今年华为的实习生笔试上机题——火星计算器,唯一的差别是运算符改变了下,用栈实现的流程是一模一样的。
/**/60ms//*/
class Solution {
public:
bool isOperator(char ch){ //判断是否是运算符
return (ch == '+' || ch == '-' || ch == '/' || ch == '*'||ch == '=');
}
char precede(char th1,char th2) /*判断两个运算符的优先级,>表示th1的优先级不低于th2的优先级*/
{
if((th1 == '*' || th1 =='/' )|| (th2 == '=') ||((th1 == '+' || th1 =='-') && (th2 == '+' || th2 =='-')))
return '>';
else
return '<';
}
int operate(int a,char opd,int b) /*进行 a op b 的运算*/
{
if(opd == '+')
return a + b;
else if(opd == '-')
return a - b;
else if(opd == '/' && b != 0)
return a / b;
else if(opd == '*')
return a * b;
else
return -1;
}
void getTwo(stack &num,int &left,int &right) /*从num中获取两个操作数,注意左右和出栈顺序*/
{
right = num.top(); /*先出栈的为右操作数*/
num.pop();
left = num.top();
num.pop();
}
int calculate(string s) /*计算运算表达式s*/
{
s.push_back('=');
int re = 0;
stack operater;
stack num;
operater.push('=');
char optrTop;
for(string::size_type i = 0;i != s.size();)
{
if(s[i] == ' ') /*跳过空格*/
{
i++;
continue;
}
optrTop = operater.top();
if(s[i] == '=' && optrTop == '=') /*运算结束条件*/
{
//cout <<"optTop: "<< optrTop <')
{
int left ,right;
getTwo(num,left,right);
char theta = operater.top();
operater.pop();
// cout <<"operater pop :" <