neat and clean java solution


  • 1
    F

    Be care to append a character which is not a digit and space to the end of s:

        public int calculate(String s) {
            Stack<Integer> stack = new Stack<>();
            int result = 0;
            int number = 0;
            char sign = '+';
            for (char c : s.concat("x").toCharArray()) {
                if (Character.isDigit(c)) {
                    number = number * 10 + c - '0';
                } else if (c != ' ') {
                    switch (sign) {
                        case '+':
                            stack.push(number);
                            break;
                        case '-':
                            stack.push(-number);
                            break;
                        case '*':
                            stack.push(stack.pop() * number);
                            break;
                        case '/':
                            stack.push(stack.pop() / number);
                    }
                    number = 0;
                    sign = c;
                }
            }
            for (Integer integer : stack) {
                result += integer;
            }
            return result;
        }

Log in to reply
 

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