zoukankan      html  css  js  c++  java
  • [LeetCode] Evaluate Reverse Polish Notation

    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

    Solution:

    需要注意operand为负数的情况。

    class Solution {
    public:
        int stringToInt(string s)
        {
            if(s.length() == 0)
                return 0;
            int p = 1;
            if(s[0] == '-') 
            {
                p = -1;
                s = s.substr(1, s.length() - 1);
            }
            int ans = s[0] - '0';
            for(int i = 1;i < s.length();i++)
                ans = ans * 10 + s[i] - '0';
            return ans * p;
        }
        
        int evalRPN(vector<string> &tokens) {
            int len = tokens.size(), ans = 0;
            int *operand = new int[len + 1], operandNum = 0;
            memset(operand, 0, (len + 1) * sizeof(int));
            
            int res = 0; // 0 for num, 1 +, 2 -, 3 *, 4 /
            for(int i = 0;i < len;i++)
            {
                if(tokens[i] == "+")
                {
                    operand[operandNum - 2] = operand[operandNum - 2] + operand[operandNum - 1];
                    operandNum--;
                }
                else if(tokens[i] == "-")
                {
                    operand[operandNum - 2] = operand[operandNum - 2] - operand[operandNum - 1];
                    operandNum--;
                }
                else if(tokens[i] == "*")
                {
                    operand[operandNum - 2] = operand[operandNum - 2] * operand[operandNum - 1];
                    operandNum--;
                }
                else if(tokens[i] == "/")
                {
                    operand[operandNum - 2] = operand[operandNum - 2] / operand[operandNum - 1];
                    operandNum--;
                }
                else
                {
                    int op = stringToInt(tokens[i]);
                    operand[operandNum++] = op;
                }
            }
            return operand[0];
        }
    };
  • 相关阅读:
    tableView的高度问题
    信任机型
    cell 内部 设置width 总不对
    图文混排
    UICollectionview实现自定义cell的移动删除
    ios 各种技术
    打包ane之后在FB上生成ipa的阶段错误
    自动布局出代码植入 的图像化实例
    MapReduce编程实例
    二叉树的遍历(递归遍历、非递归遍历、层序遍历)
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3597401.html
Copyright © 2011-2022 走看看