Java easy-understanding solution


  • 1
    Y
    public int calculate(String s) {
        if(s==null || s.length()==0) return 0;
        Stack<Integer> stack = new Stack<Integer>();
        int result = 0;
        char sign = '+';
        for(int i = 0; i < s.length(); i++){
            char temp = s.charAt(i);
            if(temp == '+' || temp == '-' || temp == '*' || temp == '/'){
                sign = temp; continue;
          }
            if((' '!=temp)){
                int j = i;
                int digit = Character.getNumericValue(temp);
                if(i < s.length() - 1){
                    j++;
                    while(j < s.length() && s.charAt(j) >= '0' && s.charAt(j) <= '9' && s.charAt(j) != ' '){
                        if(j < s.length()) j++;
                        else break;
                    }
                    digit = Integer.parseInt(s.substring(i, j));
                    i = j - 1;
                }
                switch (sign){
                    case '+' : stack.push(digit);break;
                    case '-' : stack.push(-digit);break;
                    case '*' : stack.push(stack.pop() * digit);break;
                    case '/' : stack.push(stack.pop() / digit);break;
                }
            }
        }
        for(int i: stack){
            result += i;
        }
        return result;
    }

Log in to reply
 

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