【leetcode】No.150 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


这是一道极为简单的入门级题目,考察的是对于栈的理解。当然,如果用STL的话,连理解也不用了。直接搞定。

唯一值得注意的是不要低级的造轮子。C标准库里面有的函数,就不要再自己写了,否则只是出力不讨好而已。

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        int i1 = 0, i2 = 0;
       for(auto tempStr : tokens) 
       {
           if (isdigit(tempStr[0]) || tempStr.size()>1)
           {
                s.push(atoi(tempStr.c_str()));
                continue;
           }
 
           switch(tempStr[0]){
            case '+':
                i1 = s.top(); s.pop();
                i2 = s.top(); s.pop();
                i2 += i1;
                s.push(i2);
                break;
            case '-':
                i1 = s.top(); s.pop();
                i2 = s.top(); s.pop();
                i2 -= i1;
                s.push(i2);
                break;
            case '*':
                i1 = s.top(); s.pop();
                i2 = s.top(); s.pop();
                i2 *= i1;
                s.push(i2);
                break;
            case '/':
                i1 = s.top(); s.pop();
                i2 = s.top(); s.pop();
                i2 /= i1;
                s.push(i2);
                break;
                
           }
       }
       
       i2 = s.top();
       return i2;
    }

private:
    std::stack<int> s;
};

可以看出,使用了标准C库 <cctype>中的 int isdigit(int c) 函数,如果c是数字字符,返回非0值,否则,返回0. 还使用了int atoi (const char * str); 函数,从名字可以看出,把C字符串风格的数字字符转换为数字。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值