ID | Title | Difficulty | |
---|---|---|---|
Loading... |
227. Basic Calculator II
Medium
LeetCode
Math, String, Stack
Problem
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
Code
class Solution {
public int calculate(String s) {
int len = s.length();
if(s==null || len ==0) return 0;
Stack<Integer> stack = new Stack<Integer>();
int res = 0;
int num = 0;
char sign = '+';
for(int i = 0; i < len; i++){
if(Character.isDigit(s.charAt(i))){
num = s.charAt(i) - '0';
// 如果当前数字的后边也是数字,那就要*10来得到这整个的数字
while(i + 1 < len && Character.isDigit(s.charAt(i + 1))){
num = num * 10 + s.charAt(i + 1) - '0';
i++;
}
}
// 得到一个运算符
// 不是数字也不是空格
// 注意最后一个数字,由于符号总是在数字之前,
// 因此最后一个数字无法计算,这时需要使用i == len - 1进行最后一次运算
if(!Character.isDigit(s.charAt(i)) && s.charAt(i) != ' ' || i == len - 1){
// 如果是+-就放进去
if(sign == '+') stack.push(num);
if(sign == '-') stack.push(-num);
// 如果是*/就先计算再放进去
if(sign == '*') stack.push(stack.pop() * num);
if(sign == '/') stack.push(stack.pop() / num);
sign = s.charAt(i);
num = 0;
}
}
for(int i : stack){
res += i;
}
return res;
}
}
按 <- 键看上一题!
226. Invert Binary Tree
按 -> 键看下一题!
228. Summary Ranges