227. Basic Calculator II

LeetCode

link
Stack

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
class Solution {
static int calculate(String s) {
int len= s.length();
if(s==null || len==0) return 0;
LinkedList<Integer> stack = new LinkedList<Integer>();
int num = 0;
char sign = '+';
for(int i=0;i<len;i++){
char c = s.charAt(i);
if(Character.isDigit(c)){
num = num*10+c-'0';
}
if((!Character.isDigit(c) && c!=' ') || 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 = c;
num = 0;
}
}
int total = 0;
while (!stack.isEmpty()) total += stack.pop();
return total;
}
}

0%