227. Basic Calculator II-基础计算器

本文介绍了解决227.BasicCalculatorII问题的一种高效方法。通过使用栈来存储中间结果,并在遇到乘除法时进行相应的运算,该算法能够在两次扫描内完成整个表达式的计算。这种方法在运行效率上超越了大部分同类提交。
原题链接:227. Basic Calculator II
相似博文:224. Basic Calculator | Java最短代码实现

【思路】

本题考查字符串和数学运算的结合。有两种做法:第一种做法是第一遍先扫描乘除,第二遍扫描加减;第二种做法是将中间结果暂时压入栈中,遇到乘除,则从栈顶取出元素,再进行乘除运算,过后再压栈。本解法采用第二种做法:

public class Solution {
    public int calculate(String s) {
        Stack<Integer> stack = new Stack<Integer>();
        int nums = 0, result = 0;
        char sign = '+';
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (Character.isDigit(ch)) nums = nums*10 + ch-'0';
            if ((ch == ' ' || Character.isDigit(ch)) && i < s.length()-1) continue;
            if (sign == '+') stack.add(nums);
            else if (sign == '-') stack.add(-nums);
            else if (sign == '*') stack.add(stack.pop() * nums);
            else if (sign == '/') stack.add(stack.pop() / nums);
            sign = ch;
            nums = 0;
        }
        while (!stack.isEmpty()) result += stack.pop();
        return result;
    }
}

109 / 109 test cases passed. Runtime: 35 ms  Your runtime beats 70.59% of javasubmissions.

欢迎优化!

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值