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.You may assume that the given expression is always valid.
Some examples:
"3+2*2" = 7
" 3/2 " = 1
" 3+5 / 2 " = 5
思路
- 拿到第一个数
- 拿到第一个操作符
- 拿到第二个数
- 根据操作符类型进行判断。如果是乘除对num进行更新,如果是加减,对最终结果res进行更新,并更新运算符。
- 判断最后一个运算符,如果是加减更新res
public class Solution {
public int calculate(String s) {
int res = 0, num = 0;
int index = 0;
char symbol = '+';
int len = s.length();
while(index < len && s.charAt(index) == ' ' ) {
index++;
}
while(index < len && isDigit(s.charAt(index))) {
num = num * 10 + (s.charAt(index++) - '0');
}
while(index < len){
if (index < len && s.charAt(index) == ' ' ) {
index++;
continue;
}
char symbol1 = s.charAt(index++);
int tmp = 0;
while(index < len && s.charAt(index) == ' ' ) {
index++;
}
while(index < len && isDigit(s.charAt(index))) {
tmp = tmp * 10 + (s.charAt(index++) - '0');
}
if (symbol1 == '+' || symbol1 == '-') {
if (symbol == '+'){
res += num;
}else {
res -= num;
}
num = tmp;
symbol = symbol1;
} else {
if (symbol1 == '*') {
num *= tmp;
} else {
num /= tmp;
}
}
}
if (symbol == '+') {
res += num;
} else {
res -= num;
}
return res;
}
private final boolean isDigit(char s) {
return s >= '0' && s <= '9';
}
}