资讯专栏INFORMATION COLUMN

[LintCode] Evaluate Reverse Polish Notation

luckyyulin / 2152人阅读

摘要:中的运算符,运算之后要出来,继续遍历数组。是放入新的数字,用转换为均可。

Problem

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +, -, *, /. Each operand may be an integer or another expression.

Example
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
Note

Switch中的运算符case,运算之后要break出来,继续遍历tokens数组。
default是放入新的数字,用parseInt()/valueOf()转换String为Integer均可。

Solution
public class Solution {
    public int evalRPN(String[] tokens) {
        if (tokens == null || tokens.length % 2 == 0) return 0;
        Stack stack = new Stack();
        for (String tok: tokens) {
            switch(tok) {
                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 divisor = stack.pop();
                    int dividend = stack.pop();
                    stack.push(dividend/divisor);
                    break;
                default:
                    stack.push(Integer.valueOf(tok));
            }
        }
        return stack.pop();
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/65499.html

相关文章

  • [Leetcode] Evaluate Reverse Polish Notation 计算逆波兰表

    摘要:栈法复杂度时间空间思路逆波兰表达式的计算十分方便,对于运算符,其运算的两个数就是这个运算符前面的两个数。注意对于减法,先弹出的是减号后面的数。 Evaluate Reverse Polish Notation Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operato...

    ephererid 评论0 收藏0
  • [LeetCode] 150. Evaluate Reverse Polish Notation

    Problem Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, /. Each operand may be an integer or another expression. Note: Division between two inte...

    KoreyLee 评论0 收藏0
  • 150. Evaluate Reverse Polish Notation

    摘要:题目链接来做,保存数字,碰到符号的时候就弹出两个数字计算算完后再放入,最后里面的就是结果。 150. Evaluate Reverse Polish Notation 题目链接:https://leetcode.com/problems... stack来做,保存数字,碰到符号的时候就弹出两个数字计算算完后再放入stack,最后stack里面的就是结果。 public class So...

    yanbingyun1990 评论0 收藏0
  • leetcode150. Evaluate Reverse Polish Notation

    摘要:我们一般看到的数学表达式就是中缀表达式,也就是将符号放在两个数字之间。后缀表达式也就是将运算符放在相应数字的后面。后缀表达式相当于树中的后序遍历。通过获得对应位置的操作符。如果对应的还是操作符,则继续递归往前计算。 题目要求 Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid...

    bitkylin 评论0 收藏0
  • 表达式类算法题小结

    摘要:将表达式转换为逆波兰式,然后求值转换中缀表达式为逆波兰式鲁棒性检测,表达式中没有操作数计算逆波兰式值参考 表达式类算法题小结 [TOC] 声明 文章均为本人技术笔记,转载请注明出处:[1] https://segmentfault.com/u/yzwall[2] blog.csdn.net/j_dark/ 表达式分类 根据运算符与相关操作操作数的位置不同,将表达式分为前缀,中缀和后缀表...

    Heier 评论0 收藏0

发表评论

0条评论

luckyyulin

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<