Basic Calculator

原创 2015年07月09日 15:24:35

反复练习

由于没有乘法和除法。只要记录每个数前的正负号,顺序相加即可。

public class Solution {
    public int calculate(String s) {
        //s.replaceAll(" ","");    
        if (s == null || s.length() == 0) {
            return -1;
        }
        Stack<Integer> sign = new Stack<Integer>();
        sign.push(1);
        int lastOp = 1;
        int result = 0;
        for (int i = 0; i < s.length(); i++) {
            switch (s.charAt(i)) {
            case ' ' :
                break;
            case '+' :
                lastOp = 1;
                break;
            case '-' :
                lastOp = -1;
                break;
            case '(' :
                sign.push(lastOp * sign.peek());
                lastOp = 1;
                break;
            case ')' :
                sign.pop();
                break;
            default:
                int num = 0;
                while (i < s.length() && Character.isDigit(s.charAt(i))) {
                    num = num * 10 + s.charAt(i) - '0';
                    i++;
                }
                result = result + sign.peek() * lastOp * num;
                i--;
            }
        }
        return result;
    }
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

224-m-Basic Calculator

有括号的运算,只有加减运算。很明显本题只考察括号匹配没有再加入乘除,否则就真是半个计算器的工程了。由于我是先写了计算器二式,所以本题也想用一次扫描就出结果。但由于有括号要考虑出栈,要考虑单个括号括的数...

Basic Calculator II

Implement a basic calculator to evaluate a simple expression string. The expression string contai...

第一周 leetcode 224. Basic Calculator(hard)

第一周 leetcode 224. Basic Calculator(hard)题目描述: Implement a basic calculator to evaluate a simple ex...

Leetcode Basic Calculator 系列

Implement a basic calculator to evaluate a simple expression string. The expression string contains ...

leetcode_Basic Calculator

题目: Implement a basic calculator to evaluate a simple expression string. The expression stri...

【leetcode】String——Basic Calculator II (227)

题目: Implement a basic calculator to evaluate a simple expression string. The expression string...

LeetCode No.224 Basic Calculator

LeetCode No.224 Basic Calculator

Basic Calculator

题目描述: Implement a basic calculator to evaluate a simple expression string. The expression st...

LeetCode(224) Basic Calculator

题目Implement a basic calculator to evaluate a simple expression string.The expression string may cont...

Leetcode: Basic Calculator

 Implement a basic calculator to evaluate a simple expression string. The expression string may ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)