关闭

leetcode evaluate-reverse-polish-notation

标签: leetcode
122人阅读 评论(0) 收藏 举报
分类:

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
import java.util.*;
public class Solution {
    public int evalRPN(String[] tokens) {
        Stack<Integer> s = new Stack<>();
        int a,b;
        int c;
        for(int i =0; i<tokens.length;++i)
        {
           if( tokens[i].equals("+"))
           {
               b = s.pop();
               a = s.pop();
               c = a + b;
               s.push(c);
           }else if(tokens[i].equals("-"))
           {
               b = s.pop();
               a = s.pop();
               c = a - b;
               s.push(c);
           }else if(tokens[i].equals("*"))
           {
               b = s.pop();
               a = s.pop();
               c = a * b;
               s.push(c);
           }else if(tokens[i].equals("/"))
           {
               b = s.pop();
               a = s.pop();
               c = a/b;
               s.push(c);
           }else
           {
              s.push(Integer.parseInt(tokens[i]));  
           }
            
        }
        return s.pop();
    }
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:30262次
    • 积分:873
    • 等级:
    • 排名:千里之外
    • 原创:56篇
    • 转载:15篇
    • 译文:0篇
    • 评论:8条
    最新评论