0
点赞
收藏
分享

微信扫一扫

[数组]NC216 逆波兰表达式求值-简单

​​NC216 逆波兰表达式求值​​

描述

给定一个逆波兰表达式,求表达式的值。


数据范围:表达式长度满足  ,表达式中仅包含数字和 + ,- , * , / ,其中数字的大小满足 

示例1

输入:

["2","1","+","4","*"]

复制

返回值:

12

复制

示例2

输入:

["2","0","+"]

复制

返回值:

2

题解

代码如下:

#include <bits/stdc++.h>

using namespace std;

// ["2","1","+","4","*"]
int calc(int a, int b, char x)
{
if (x == '+')
{
return a + b;
}
else if (x == '-')
{
return a - b;
}
else if (x == '*')
{
return a * b;
}
return a / b;
}

int evalRPN(vector<string> &tokens)
{
std::stack<int> nums;
for (auto &s : tokens)
{
if (s.size() == 1 && (s[0] == '+' || s[0] == '-' || s[0] == '*' || s[0] == '/'))
{
int a = nums.top();
nums.pop();
int b = nums.top();
nums.pop();
nums.push(calc(b, a, s[0]));
}
else
{
nums.push(std::atoi(s.c_str()));
}
}
return nums.top();
}

举报

相关推荐

0 条评论