[leetcode] 227. Basic Calculator II

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.

这道题是完成一个包含加减乘除的计算器,题目难度为Medium。

我们知道,乘除的优先级比加减高,因此我们需要优先计算乘除的结果。遍历整个表达式,遇到‘+’或‘-’时表明之前的乘除(或没有)已经结束,此时可以对前面的乘除结果(没有乘除即是一个单独数字)进行计算了。在遇到‘*’或‘/’时不能立即将之前出现的数字进行计算,而要将乘除的结果缓存起来等待‘+’或‘-’的出现。具体代码:

class Solution {
public:
    int calculate(string s) {
        int num = 0, rst = 0;
        int lastNum = 0;
        int markOp = 1, lastOp = 1; //1:+, -1:-, 2:*, 3:/
        
        s += "+";
        for(auto ch:s) {
            if(ch >= '0' && ch <= '9') {
                num = num*10+ch-'0';
            }
            else if(ch == ' ') {
                continue;
            }
            else {
                if(lastOp < 2) lastNum = num;
                else if(lastOp == 2) lastNum *= num;
                else lastNum /= num;
                num = 0;
                
                if(ch == '+' || ch == '-') {
                    rst += markOp * lastNum;
                    markOp = (ch == '+') ? 1 : -1;
                    lastOp = markOp;
                    lastNum = 0;
                }
                else {
                    lastOp = (ch == '*') ? 2 : 3;
                }
            }
        }
        
        return rst;
    }
};

数字的处理就不再详述了,在遇到运算符时,根据上一个运算符的类型进行不同的处理,如果上一个运算符是‘+’或‘-’,把当前数字缓存起来等候处理(如果当前运算符是‘*’或‘/’,缓存起来的数据就是乘除运算的初始数值);如果上一个运算符是‘*’或‘/’,说明乘除运算已经开始,用缓存的乘除结果对当前数值进行乘除作为新的乘除结果缓存起来。

如果当前运算符是’+‘或’-‘,表明之前的乘除(或没有)已经结束,可以将其结果运算到最终结果中了,用我们记录下来的上一个加减运算的运算符(markOp)对乘除结果(没有乘除运算就是一个单独的数字)进行计算,同时修改上一个运算符标志以及上一个加减运算符标志,并将记录的乘除运算缓存清零。如果当前运算符是’*‘或’/‘,修改上一个运算符标志即可。听起来可能很绕,可以直接查看代码再和解释比对来理解。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值