yokostan / Leetcode-Solutions

Doing exercise on Leetcode. Carry on!
0 stars 3 forks source link

Leetcode #227. Basic Calculator II #218

Open yokostan opened 5 years ago

yokostan commented 5 years ago
class Solution {
    public int calculate(String s) {
        int res = 0;
        int num = 0;
        char sign = '+';
        if (s == null || s.length() == 0) return res;
        Stack<Integer> stack = new Stack<>();

        for (int i = 0; i < s.length(); i++) {
            if (Character.isDigit(s.charAt(i))) {
                num = num * 10 + s.charAt(i) - '0';
            }
            if((!Character.isDigit(s.charAt(i)) &&' '!=s.charAt(i)) || i==s.length()-1) {
                if (sign == '+') stack.push(num);
                if (sign == '-') stack.push(-num);
                if (sign == '*') stack.push(stack.pop()*num);
                if (sign == '/') stack.push(stack.pop()/num);
                num = 0;
                sign = s.charAt(i);
            }
        }

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

        return res;
    }
}

As we can only store one type of data in our Stack, it will be very wise to only store the positive calculated results and add them up all in the end!