java: Reverse Polish notation (postfix expression)

Use reverse Polish notation to calculate the value of an arithmetic expression.

The valid operators are +, -, *, /. Each operand can be an integer or another expression.

example:

 ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9

 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
public class Solution(){
 public int evalRPN(String[] tokens){
  //在这里写上你的代码
}
}

[Knowledge Points]: Use the stack.
Traverse each digit and symbol in the expression from left to right, push the stack when it encounters a number, and push the two digits at the top of the stack when it encounters a symbol, perform the operation, and push the result of the operation (the result replaces the operation Two numbers) until the final result is obtained.

       //代码语言组织
/**1.需要创建一个存放整数的栈:**/
import java.util.Stack;
Stack<Integer>stack = new Stack<Integer>();

/**2.要将String类型的数组tokens里的元素进栈**/
 for(int i=0;i<tokens.length();i++){
   int num=Integer.parseInt(tokens[i]);
   stack.add(num);
}

/**3.但我们知道第二步的代码会有报错的,当tokens数组里包含非数字元素时。
因为该 String 不能作为 int 分析,则抛出NumberformatException异常。所以我们可以利用这一点做一个异常处理**/
   for(int i=0;i<tokens.length();i++){
   try{
   int num=Integer.parseInt(tokens[i]);
   stack.add(num);}
   catch(Exception e){
   }
}

/**4.最后再在catch里写一个方法做计算的处理**/
catch(Exception e){
//取栈顶元素出来运算
  int a=stack.pop();
  int b=stack.pop();
  calculte(a,b,tokens[i]);

   }
public int calculate(){
  switch(opera){
      case "+":return a+b;
      case "-":return a-b;
      case "*":return a*b;
      case "/":return a/b;
      default:return 0;
  }
}

but! ! This code does not pass all test cases

Fail your code. The saved answer is wrong: The program you submitted did not pass all test cases. The pass rate is 5.88%.

Test case: ["0","3","/"]

The corresponding output should be:

0

Your output is:

java.lang.ArithmeticException: / by zero

So we have to consider another division by 0

//解决了除0的情况
case "/":
try{
   
   return a/b;}
catch(Exception e){
          return 0;
      }

But in the end, it failed

Test case: ["3","4","-"]

The corresponding output should be:

1

Your output is:
-1
At this time, I want to understand. The reason why the code fails is not because I didn't consider division by 0. It is because multiplication and addition do not care about the order of operands in operations, while subtraction and division must consider order. Some can pass because multiplication and addition do not consider order.
Think about it, the reverse Polish notation is to traverse from left to right, so [Result] = [Left Number] (Symbol) [Right Number]
So the code needs to be changed like this

case "+":return b+a;
case "-":return b-a;
case "-":return b-a;
case "/":return b/a;

AC code:

import java.util.*;
public class Solution {
    public int evalRPN(String[] tokens) {
        //后缀表达式
        //建栈
   Stack<Integer>stack=new   Stack<Integer>();
     for(int i=0;i<tokens.length;i++){
       try{
       int num=Integer.parseInt(tokens[i]);
       stack.add(num);}
       catch(Exception e){
        //取栈顶元素(出栈)
          int a=stack.pop();
          int b=stack.pop();
          //calculate(a,b,tokens[i]);
          stack.add(calculate(a,b,tokens[i]));
      }
   }
   //到最后栈里只剩一个元素,所以取栈顶就可以
   return stack.pop();     
    }
    public int calculate(int a,int b,String opera){
      switch(opera){

      case "+":return b+a;
      case "-":return b-a;
      case "*":return b*a;
      case "/":return b/a;
      default:return 0;
  }

}

Write picture description here

Guess you like

Origin blog.csdn.net/sinat_35803474/article/details/70141676