Basic Calculator

给输入为string,例如"2+3-999",之包含+-操作,返回计算结果。

public int basicCalculator(String expression)
    {
        if(expression == null || expression.length() == 0)
        {
            return 0;
        }

        Stack<Integer> stack = new Stack<Integer>();
        char preSign  = '+';
        int num = 0;
        for(int i = 0; i< expression.length(); i++)
        {
            char current  = expression.charAt(i);
            if(isNumber(current))
            {
                num = num * 10 + (current - '0');
            }
            // 这里注意要分开写
            if(!isNumber(current) || i == expression.length()-1)
            {
                switch(preSign)
                {
                    case '+': stack.push(num); break;
                    case '-': stack.push(-num); break;
                }
                preSign = current;
                num = 0;
            }
        }

        int res = 0;
        while(!stack.isEmpty())
        {
            res += stack.pop();
        }
        return res;
    }

    public boolean isNumber(char c)
    {
        return c >= '0' && c <= '9';
    }

Last updated