题目描述:
给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。
整数除法仅保留整数部分。
提示:
- 1 <= s.length <= 3 * 105
- s 由整数和算符 (’+’, ‘-’, ‘*’, ‘/’) 组成,中间由一些空格隔开
- s 表示一个 有效表达式,表达式中的所有整数都是非负整数,且在范围 [0, 231 - 1] 内
- 题目数据保证答案是一个 32-bit 整数
示例 1:
输入:s = “3+2*2”
输出:7
示例 2:
输入:s = " 3/2 "
输出:1
示例 3:
输入:s = " 3+5 / 2 "
输出:5
代码如下:
class Solution {
public int calculate(String str) {
String s = str.trim();
int n = s.length();
Stack<Integer> stack = new Stack<>();
int num = 0;
char sign = '+';
for (int i = 0; i < n; i++) {
char ch = s.charAt(i);
if (Character.isSpaceChar(ch)) {
continue;
}
if (Character.isDigit(ch)) {
num = 10 * num + (ch - '0');
}
if (!Character.isDigit(ch) || i == n - 1) {
if (sign == '+') {
stack.push(num);
} else if (sign == '-') {
stack.push(-num);
} else if (sign == '*') {
stack.push(stack.pop() * num);
} else if (sign == '/') {
if (num != 0) {
stack.push((int) (stack.pop() / num));
}
}
sign = ch;
num = 0;
}
}
int ans = 0;
while (!stack.isEmpty()) {
ans += stack.pop();
}
return ans;
}
}
执行结果: