-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path227.basic-calculator-ii.java
61 lines (54 loc) · 1.67 KB
/
227.basic-calculator-ii.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
class Solution {
HashSet<Character> hst;
int i;
public int calculate(String s) {
Stack<Character> oper = new Stack<Character>();
Stack<Integer> numb = new Stack<Integer>();
hst = new HashSet<Character>();
hst.add('+');
hst.add('*');
hst.add('-');
hst.add('/');
i = 0;
while(i<s.length()){
char c = s.charAt(i);
if(Character.isWhitespace(c)){
i++;
continue;
}
if(hst.contains(c)){
// System.out.println(c+" "+numb.peek()+" "+den);
if(c != '+'){
i++;
int den = getnum(s);
if(c-'/' == 0)
numb.push(numb.pop()/den);
else if(c == '*')
numb.push(numb.pop()*den);
else
numb.push(den*-1);
}else
i++;
}
else{
numb.push(getnum(s));
}
}
while(numb.size() > 1){
numb.push(numb.pop()+numb.pop());
// ope.pop();
}
return numb.pop();
}
public int getnum(String s){
int num = 0;
while(i<s.length() && Character.isWhitespace(s.charAt(i)))
i++;
while(i<s.length() && !hst.contains(s.charAt(i)) && !Character.isWhitespace(s.charAt(i))){
num = num*10 + (s.charAt(i)-'0');
i++;
}
// System.out.println(i+" i ");
return num;
}
}