-
Notifications
You must be signed in to change notification settings - Fork 0
/
227-BasicCalculator2.java
42 lines (41 loc) · 1.27 KB
/
227-BasicCalculator2.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Solution {
public int calculate(String s) {
int ans = 0;
int prev = 0;
int num = 0;
char op = '+';
for(int i=0;i<s.length();i++){
if(s.charAt(i)==' ')
continue;
else if(Character.isDigit(s.charAt(i))){
num = s.charAt(i)-'0';
while(i+1<s.length() && Character.isDigit(s.charAt(i+1))){
num = num*10 + (s.charAt(i+1)-'0');
i++;
}
switch(op){
case '+': ans += num;
prev = num;
num = 0;
break;
case '-': ans -= num;
prev = -num;
num = 0;
break;
case '*':ans = ans - prev + prev*num;
prev = prev*num;
num = 0;
break;
case '/':ans = ans - prev + prev/num;
prev = prev/num;
num = 0;
break;
}
}
else{
op = s.charAt(i);
}
}
return ans;
}
}