AB4 逆波兰表达式求值
牛客:
问题描述:
描述
给定一个逆波兰表达式,求表达式的值。
数据范围:表达式长度满足 1≤n≤104 1≤n≤104 ,表达式中仅包含数字和 + ,- , * , / ,其中数字的大小满足 ∣val∣≤200 ∣val∣≤200 。
示例1
输入:
[“2”,“1”,“+”,“4”,“*”]
返回值:
12
示例2
输入:
[“2”,“0”,“+”]
返回值:
2
AC代码
栈stack,后进先出。
stoi : string to int
stod: string to double
#include <string>
#include <vector>
#include <stdlib.h>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param tokens string字符串vector
* @return int整型
*/
int evalRPN(vector<string>& tokens) {
// write code here
int sized = tokens.size();
vector<string> stack;
int Fi_result = 0.0;
for(int i=0;i<sized;i++){
string temp = tokens[i];
if(temp == "+" || temp == "-" || temp == "*"|| temp == "/"){ //op
int a = stoi(stack.back());
stack.pop_back();
int b = stoi(stack.back());
stack.pop_back();
int temp_result;
if(temp == "+" ){
temp_result = a + b;
}
else if(temp == "-"){
int temp_num = a;
a = b;
b = temp_num;
temp_result = a - b;
}
else if(temp == "/"){
int temp_num = a;
a = b;
b = temp_num;
temp_result = a / b;
}
else{
temp_result = a * b;
}
string temp_re_string = to_string(temp_result);
// itoa(temp_result,temp_re_string,16);
stack.push_back(temp_re_string);
}
else{//num
stack.push_back(temp);
}
}
Fi_result = stod(stack.back());
return Fi_result;
}
};