Accepted clean Java solution


  • 29
    public int evalRPN(String[] a) {
      Stack<Integer> stack = new Stack<Integer>();
      
      for (int i = 0; i < a.length; i++) {
        switch (a[i]) {
          case "+":
            stack.push(stack.pop() + stack.pop());
            break;
              
          case "-":
            stack.push(-stack.pop() + stack.pop());
            break;
              
          case "*":
            stack.push(stack.pop() * stack.pop());
            break;
    
          case "/":
            int n1 = stack.pop(), n2 = stack.pop();
            stack.push(n2 / n1);
            break;
              
          default:
            stack.push(Integer.parseInt(a[i]));
        }
      }
      
      return stack.pop();
    }

  • 0
    C

    nice and clean


  • -2
    E

    yeah,I got the same implementation. using stack.

    public class Solution {
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<Integer>();
        for(String token:tokens){
            if(token.equals("+")){
                stack.push(stack.pop() + stack.pop());
            }else if(token.equals("-")){
                stack.push(-stack.pop() + stack.pop());
            }else if(token.equals("*")){
                stack.push(stack.pop() * stack.pop());
            }else if(token.equals("/")){
                int num1=stack.pop();
                int num2=stack.pop();
                stack.push( num2/ num1);
            }else{
                stack.push(Integer.valueOf(token));
            }
        }
        return stack.isEmpty()?0:stack.pop();
    }
    

    }


  • 1
    A

    great solution! why I use stack.push((1/stack.pop())*stack.pop());
    in case 4 is not ok?


  • 1
    F

    @Ayu1991house said in Accepted clean Java solution:

    reat solution! why I use stack.push((1/stack.pop())*stack.pop());
    in case 4 is not ok?

    num2 / num1 is not the same as (1 / num1) * num2 because 1 / num1 would be 0 for any integer num1 > 1.

    E.g: num1 = 2, num2 = 4
    num2 / num1 = 2
    (1 / num1) * num2 = 0


  • 1

    Very nice handle of "-"!


  • 0
    Y
    This post is deleted!

  • 0
    A

    @jeantimex For python users - the division causes some problems. Ex) 8//-64


Log in to reply
 

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