Simple Java solution from Calculator I. Beats 90%


  • 0
    public class Solution {
        public int calculate(String s) {
            Stack<Integer> stack = new Stack<Integer>();
            s = s.trim();
            int sum = 0;
            int number = 0;
            int sign = 1;
            for(int i = 0; i <= s.length(); i++) {
                if(i == s.length()) {
                    if(!stack.isEmpty()) number = stack.pop() / number;
                    sum += sign * number;
                    break;
                }
                char c = s.charAt(i);
                if(c == ' ') continue;
                if (Character.isDigit(c)) {
                    number = number * 10 + c - '0';
                } else {
                    if(!stack.isEmpty()) {
                        number = stack.pop() / number;
                    }
                    if (c == '+') {
                        sum += sign * number;
                        sign = 1;
                        number = 0;
                    } else if (c == '-') {
                        sum += sign * number;
                        sign = -1;
                        number = 0;
                    } else if (c == '*') {
                        sign *= number;
                        number = 0;
                    } else if (c == '/') {
                        stack.push(number * sign);
                        number = 0;
                        sign = 1;
                    }
                }
                
            }
            return sum;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.