给你一个字符串表达式 s
,请你实现一个基本计算器来计算并返回它的值。
整数除法仅保留整数部分。
你可以假设给定的表达式总是有效的。所有中间结果将在 [-231, 231 - 1]
的范围内。
注意:不允许使用任何将字符串作为数学表达式计算的内置函数,比如 eval()
。
示例 1:
输入:s = "3+2*2" 输出:7
示例 2:
输入:s = " 3/2 " 输出:1
示例 3:
输入:s = " 3+5 / 2 " 输出:5
提示:
1 <= s.length <= 3 * 105
s
由整数和算符('+', '-', '*', '/')
组成,中间由一些空格隔开s
表示一个 有效表达式- 表达式中的所有整数都是非负整数,且在范围
[0, 231 - 1]
内 - 题目数据保证答案是一个 32-bit 整数
stack:
class Solution {
public:
int calculate(string s) {
stack<int> nums; // 栈,用于存储操作数
int currentNum = 0; // 当前解析的数字
char operation = '+'; // 初始运算符为加号
int n = s.size(); // 表达式的长度
for (int i = 0; i < n; i++) {
char c = s[i];
// 如果是数字,解析出完整的数字
if (isdigit(c)) {
currentNum = currentNum * 10 + (c - '0');
}
// 如果当前字符是运算符或遍历到最后一个字符
if ((!isdigit(c) && c != ' ') || i == n - 1) {
if (operation == '+') {
nums.push(currentNum); // 加法,将数字压入栈
} else if (operation == '-') {
nums.push(-currentNum); // 减法,将负值压入栈
} else if (operation == '*') {
int top = nums.top(); nums.pop();
nums.push(top * currentNum); // 乘法,栈顶元素乘以当前数字
} else if (operation == '/') {
int top = nums.top(); nums.pop();
nums.push(top / currentNum); // 除法,栈顶元素除以当前数字
}
operation = c; // 更新当前的运算符
currentNum = 0; // 重置当前数字
}
}
// 累加栈中的所有数字,得到最终结果
int result = 0;
while (!nums.empty()) {
result += nums.top();
nums.pop();
}
return result;
}
};
isdigit(c)
: 这是一个标准库函数,用来判断字符 c
是否是数字字符。它返回一个布尔值:如果 c
是数字字符(例如 '0'
到 '9'
),则返回 true
。否则,返回 false
。
currentNum = currentNum * 10 + (c - '0');:每当遇到一个新数字时,将 currentNum
乘以 10,这是为了确保新的数字进入正确的位置。例如,如果 currentNum
已经是 12
,遇到字符 '3'
时,就会变成 120 + 3 = 123
。
举例" 3+5 / 2 ":
- 读到3时,currentNum = 3
- 读到 ‘+’时,由于初始化的operation为 ‘+’,将
3
压入栈,operation
更新为+
,currentNum
重置为 0。 - 读到 ‘5’时,currentNum = 5
- 读到 ‘/ ’时,由于上一个operation为 ‘+’,因此将
5
压入栈,operation
更新为/
,currentNum
重置为 0。 - 读到 ‘2’时,currentNum = 2,
- 由于是最后一个字符,我们需要根据当前的运算符
/
进行除法操作,将 5 / 2 = 2 压入栈
最后栈中元素相加,栈中的数字为 [3, 2]
,将它们相加 result = 3 + 2 = 5;otr:
vector:
class Solution {
public:
int calculate(string s) {
vector<int> stk;
int n = s.size();
char preSign = '+'; // 初始运算符设为 '+'
long num = 0;
for(int i = 0;i < n; ++i) {
if (isdigit(s[i])) {
num = num * 10 + s[i] - '0'; // 处理多位数
}
if(!isdigit(s[i]) && s[i] != ' ' || i == n - 1){
if(preSign == '+') stk.push_back(num);
else if(preSign == '-') stk.push_back(-num);
else if(preSign == '*') stk[stk.size() - 1] *= num;
else if(preSign == '/') stk[stk.size() - 1] /= num;
num = 0;
preSign = s[i];
}
}
return accumulate(stk.begin(), stk.end(), 0);
}
};
accumulate
被用于将栈 stk
中所有元素相加,以计算最终结果。0
作为第三个参数是指accumulate
从 0
开始累加。