Basic Calculator II - LeetCode 227

题目描述:

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;
	}
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值