题目原址
https://leetcode.com/problems/basic-calculator-ii/description/
题目描述
Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero.
Example 1:
Input: “3+2*2”
Output: 7
Example 2:
Input: ” 3/2 ”
Output: 1
Example 3:
Input: ” 3+5 / 2 ”
Output: 5
Note:
- You may assume that the given expression is always valid
- Do not use the eval built-in library function.
解题思路
给定一个字符串,字符串包含数字和+、-、*、/
运算符,按照给定字符串求字符串的结果
使用栈来存储中间的运算结果,对于+和-的操作直接放如栈中,对于*和/的操作先从栈中取出一个数计算然后再放入栈中。sign记录的是上一次的运算符,sign初始值为+,因为首先栈中应该有值才能进行操作,所以第一个数一定要压入栈中。
AC代码
class Solution {
public int calculate(String s) {
Stack<Integer> stack = new Stack<>();
if(s.length() == 0) return s.charAt(0) - '0';
int num = 0;
char sign = '+';
for(int i = 0; i < s.length(); i++) {
if(Character.isDigit(s.charAt(i))) {
num = num * 10 + s.charAt(i) - '0';
}
if((!Character.isDigit(s.charAt(i)) && s.charAt(i) != ' ') || i == s.length() - 1) {
//操作数为+的直接压栈,为-的则将其负数压栈
if(sign == '+') {
stack.push(num);
}else if(sign == '-') {
stack.push(-num);
}
//如果是*和/的操作就先从栈中取出一个数进行计算,再将其放入栈中
if(sign == '*') {
stack.push(stack.pop() * num);
}else if(sign == '/') {
stack.push(stack.pop() / num);
}
//更改运算符,并将num值置0
sign = s.charAt(i);
num = 0;
}
}
int ret = 0;
for(int i: stack) {
ret += i;
}
return ret;
}
}