-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBasic Calculator II.java
More file actions
36 lines (34 loc) · 993 Bytes
/
Copy pathBasic Calculator II.java
File metadata and controls
36 lines (34 loc) · 993 Bytes
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
class Solution {
public int calculate(String s) {
if(s.length() == 0 || s == null)
return 0;
Stack<Integer> stack = new Stack<Integer>();
int num = 0;
char sign = '+';
for(int i = 0; i<s.length(); i++)
{
char c = s.charAt(i);
if(Character.isDigit(c))
{
num = num*10 + c-'0';
}
if((!Character.isDigit(c) && ' '!=c) || i==s.length()-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 res = 0;
for(int i:stack)
res += i;
return res;
}
}