实现计算(+-*/)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.

解决:

① 注意优先级问题,由于存在运算优先级,使用一个栈保存数字,如果该数字之前的符号是加或减,那么把当前数字压入栈中,注意如果是减号,则加入当前数字的相反数,因为减法相当于加上一个相反数。如果之前的符号是乘或除,那么从栈顶取出一个数字和当前数字进行乘或除的运算,再把结果压入栈中,那么完成一遍遍历后,所有的乘或除都运算完了,再把栈中所有的数字都加起来就是最终结果了。

class Solution { //26ms
    public int calculate(String s) {
        int res = 0;
        int num = 0;
        char sign = '+';
        Stack<Integer> nums = new Stack<>();
        for (int i = 0;i < s.length();i ++){
            char c =s.charAt(i);
            if (c >= '0' && c <= '9'){
                num = num * 10 + c - '0';
            }
            if ((c <'0' && c != ' ') || i == s.length() - 1){
                if (sign == '+'){
                    nums.push(num);
                }
                if (sign == '-'){
                    nums.push(-num);
                }
                if (sign == '*' || sign == '/'){
                    int tmp = sign == '*' ? nums.pop() * num : nums.pop() / num;
                    nums.push(tmp);
                }
                sign = c;
                num = 0;
            }
        }
        while (! nums.isEmpty()){
            res += nums.pop();
        }
        return res;
    }
}

② 在discuss中看到的

class Solution { //17ms
    public int calculate(String s) {
        int cur = 0, res = 0, prod = 1;
        char prevOp = '+';
        for (int i = 0; i <= s.length(); i++) {
            char c = i < s.length() ? s.charAt(i) : '+';
            if (c == ' ') {
                continue;
            }
            else if (c >= '0' && c <= '9') {
                cur = cur * 10 + (c - '0');
            } else {
                int tmp;
                if (prevOp == '/') {
                    tmp = prod / cur;
                } else {
                    tmp = prod * cur;
                }
                if (c == '+' || c == '-') {
                    res += tmp;
                    prod = c == '+' ? 1 : -1;
                } else {
                    prod = tmp;
                }
                cur = 0;
                prevOp = c;                
            }
        }
        return res;
    }
}

转载于:https://my.oschina.net/liyurong/blog/1591497

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值