Leetcode 448. 150. Evaluate Reverse Polish Notation JAVA语言

1
2
3
4
5
6
7
8
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Some examples:
   ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
   ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
 
 
Subscribe to see which companies asked this question.

题意:求逆波兰表达式的结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public  class  Solution {
     public  int  isopnd(String s){
         if (s.length()!= 1 ) return  0 ;
             char  c=s.charAt( 0 );
             switch (c){
                 case  '+' return  1 ;
                 case  '-' return  2 ;
                 case  '*' return  3 ;
                 case  '/' return  4 ;
                 default : return  0 ;
             }
         }
     public  int  evalRPN(String[] tokens) {
         if (tokens.length== 1 return  Integer.valueOf(tokens[ 0 ]);
         Stack<Integer> stack= new  Stack<Integer>();
         int  ans= 0 ;
         for (String tk : tokens){
             int  op=isopnd(tk);
             if (op!= 0 ){
             int  a=stack.peek();
             stack.pop();
             int  b=stack.peek();
             stack.pop();
             if (op== 1 ){
                 ans=a+b;
             }
             if (op== 2 ){
                 ans=b-a;
             }
             if (op== 3 ){
                 ans=a*b;
             }
             if (op== 4 ){
                 ans=b/a;
             }
             System.out.println(ans);
             stack.push(ans);
         } else {
             stack.push(Integer.valueOf(tk));
         }
         }
         return  ans;
     }
}

PS:用栈。第一次调用栈。遇到数字,入栈,遇到运算符,出栈俩数字做计算,结果再入栈。'



本文转自 努力的C 51CTO博客,原文链接:http://blog.51cto.com/fulin0532/1902571

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值