-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCalculate.java
More file actions
99 lines (88 loc) · 2.68 KB
/
Copy pathCalculate.java
File metadata and controls
99 lines (88 loc) · 2.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package stack;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
class Calculate {
List<Character> symbels = new ArrayList<Character>(){{
add('+');
add('-');
add('*');
add('/');
}};
Stack<Character> symbel = new Stack();
Stack<Integer> nums = new Stack<>();
public int calculate(String s) {
resoution(s);
int result = 0;
while (!nums.isEmpty()){
result += nums.pop();
}
return result;
}
private void resoution(String s) {
int j = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(symbels.contains(c)){
int base = 1;
int integrate = 0;
while(j>0){
Integer pop = nums.pop();
int temp = pop * base;
integrate += temp;
base = base*10;
j--;
}
if(symbel.size() > 0){
Character peek = symbel.peek();
if(peek == '*'){
Integer pop = nums.pop();
integrate = pop * integrate;
}else if(peek == '/'){
Integer pop = nums.pop();
integrate = pop / integrate;
}else if(peek == '-'){
integrate = -integrate;
}
}
nums.push(integrate);
symbel.push(c);
}else{
if(c != ' '){
j ++;
nums.push(c - '0');
}
if(i + 1 == s.length()){
int base = 1;
int integrate = 0;
while(j>0){
Integer pop = nums.pop();
int temp = pop * base;
integrate += temp;
base = base*10;
j--;
}
nums.push(integrate);
}
}
}
Character peek = symbel.peek();
Integer first = nums.pop();
Integer second = nums.pop();
int top = 0;
if(peek == '*'){
top = first * second;
}else if(peek == '/'){
top = second / first;
}else if(peek == '-'){
top = second - first;
}else{
top = second + first;
}
nums.push(top);
}
public static void main(String[] args) {
int calculate = new Calculate().calculate("1 + 1");
System.out.println(calculate);
}
}