您的位置:首页 > 其它

Basic Calculator II - LeetCode 227

2015-06-27 11:24 411 查看
题目描述:

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.

Credits:

Special thanks to @ts for adding this problem and creating all test cases.

Hide Tags String

分析:看到这道题,第一感觉是怎么又是计算器,都快写烂了。好吧,思路参照224 Basic Calculator

,唯一的差别就是本题少了括号,多了*和/,这就要求在做运算前必须先判断优先级。不多说,代码类似于今年华为的实习生笔试上机题——火星计算器,唯一的差别是运算符改变了下,用栈实现的流程是一模一样的。

/**/////////////////////////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<int> &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<char> operater;
stack<int> 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 <<endl;
if(num.size()==1)
re = num.top();
break;
}
if(isOperator(s[i])) /*处理操作符*/
{
if(!operater.empty())
{
//cout <<"optTop  s[" << i << "] :" << optrTop<< " " << s[i]<< endl;
char prio = precede(optrTop,s[i]);
if(prio == '>')
{
int left ,right;
getTwo(num,left,right);
char theta = operater.top();
operater.pop();
//	cout <<"operater pop :" <<theta << endl;
num.push((operate(left,theta,right)));
//cout <<"num push :" << operate(left,theta,right) << endl;

}
else
{
operater.push(s[i]);
i++;
//cout <<"operater push :" << s[i]<< endl;
}
}
}
else /*处理操作数,考虑到多位整数,需要遍历到不为数字的字符为止*/
{
int tmp = 0;
while(s[i] != ' ' && !isOperator(s[i]) && i != s.size())
{
tmp = tmp * 10 + (s[i]-'0');
i++;
}
num.push(tmp);
//cout <<"num push :" << tmp<< endl;
}
}
//cout << num.size()<< endl;
return re;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: