227.Basic Calculator II

https://leetcode.com/problems/basic-calculator-ii/discuss/63003/Share-my-java-solution

class Solution {
    public int calculate(String s) {
        if(s == null || s.length() == 0)
            return 0;
        int n = s.length();
        Deque<Integer> stack = new ArrayDeque<>();
        int num = 0;
        char sign = '+';
        for(int i = 0; i < n; i++){
            if(Character.isDigit(s.charAt(i))){
                num = num * 10 + s.charAt(i) - '0';
            }

            if(!Character.isDigit(s.charAt(i)) && ' ' !=  s.charAt(i) || i == n - 1){
                if(sign == '-'){
                    stack.push(-num);
                }
                else if(sign == '+')
                    stack.push(num);
                else if(sign == '*')
                    stack.push(stack.pop() * num);
                else 
                    stack.push(stack.pop() / num);
                sign = s.charAt(i);
                num = 0;
            }
        }
        int ans = 0;
        while(!stack.isEmpty()){
            ans += stack.pop();
        }
        return ans;
    }
}

results matching ""

    No results matching ""