LeetCode编程算法题 2
计算逆波兰式(后缀表达式)的值
运算符仅包含"+","-","“和”/",被操作数可能是整数或其他表达式
例如:
[“20”, “10”, “+”, “30”, ""] -> ((20 + 10) * 30) -> 900
[“40”, “130”, “50”, “/”, “+”] -> (40 + (130 / 50)) -> 42
class Solution {
public:
/**
*
* @param tokens string字符串vector
* @return int整型
*/
int evalRPN(vector<string>& tokens) {
// write code here
int result = 0;
stack<int> digits;
int digit1 = 0, digit2 = 0;
for(int i = 0; i <tokens.size(); i++) {
if(tokens[i] == "+" ||
tokens[i] == "-" ||
tokens[i] == "*" ||
tokens[i] == "/") {
if(digits.size() < 2) return 0;
digit2 = digits.top(); // 顺序要确认对
digits.pop();
digit1 = digits.top();
digits.pop();
if(tokens[i] == "+") {
digits.push(digit1+digit2);
} else if(tokens[i] == "-") {
digits.push(digit1-digit2);
} else if(tokens[i] == "*") {
digits.push(static_cast<int>(double(digit1)*digit2));
} else if(tokens[i] == "/") {
digits.push(static_cast<int>(double(digit1)/digit2));
}
} else {
int num = stoi(tokens[i], 0, 10);
digits.push(num);
}
}
return digits.top();
}
};
1、C++ 堆栈 stack<> , push()、top()、pop()、size()、empty()
2、字符串 整数转换函数
atoi()
stoi() (C++11)
stringstream
引用 C++中的字符串(String)和数值转换
3、浮点数取整
floor()、ceil()、round()、
static_cast(double(num1)/num2)) 类型转换向0方向靠拢