-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBasicCalculatorII.java
More file actions
73 lines (68 loc) · 1.68 KB
/
Copy pathBasicCalculatorII.java
File metadata and controls
73 lines (68 loc) · 1.68 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
import java.util.Stack;
public class BasicCalculatorII {
public int calculate(String s) {
Stack<Integer> nums = new Stack<>();
Stack<Character> op = new Stack<>();
char[] ss = s.toCharArray();
int num = 0; boolean flag = false;
for(int i = 0; i < ss.length; i++){
while(i < ss.length && ss[i] == ' ') i++;
while(i < ss.length && Character.isDigit(ss[i])){
num = num * 10 + ss[i] - '0';
i++;
flag = true;
}
if(flag){
nums.push(num);
num = 0;
flag = false;
}
while(i < ss.length && ss[i] == ' ') i++;
if(i < ss.length){
if(ss[i] == '*'){
int num1 = nums.pop();
int num2 = 0;
i++;
while(i < ss.length && ss[i] == ' ') i++;
while(i < ss.length && Character.isDigit(ss[i])){
num2 = num2 * 10 + ss[i] - '0';
i++;
}
i--;
nums.push(num1 * num2);
}else if(ss[i] == '/'){
int num1 = nums.pop();
int num2 = 0;
i++;
while(i < ss.length && ss[i] == ' ') i++;
while(i < ss.length && Character.isDigit(ss[i])){
num2 = num2 * 10 + ss[i] - '0';
i++;
}
i--;
nums.push(num1 / num2);
}else{
op.push(ss[i]);
}
}
}
Stack<Integer> numss = new Stack<>();
while(!nums.isEmpty()) numss.push(nums.pop());
Stack<Character> opp = new Stack<>();
while(!op.isEmpty()) opp.push(op.pop());
while(!opp.isEmpty()){
int num1 = numss.pop();
int num2 = numss.pop();
if(opp.pop() == '+'){
numss.push(num1 + num2);
}else{
numss.push(num1 - num2);
}
}
return numss.pop();
}
public static void main(String[] args) {
BasicCalculatorII calc = new BasicCalculatorII();
System.out.println(calc.calculate("2/2 *3 + 1"));
}
}