-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcalculatorII.java
More file actions
68 lines (68 loc) · 2.07 KB
/
calculatorII.java
File metadata and controls
68 lines (68 loc) · 2.07 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
public class calculatorII {
public static void main(String[] args){
String s = "1 + 2 - 4 ";
System.out.println(calculate(s));
int[] index = {0};
String s1 = "1 + (2 - 4) ";
System.out.println(calculateII(s1, index));
}
/* 只有 +, -, , (, )
我的思路是,把括号里面的当做sub problem
对于最基本的subproblem: 只有 +,-,' '
* */
// 这是最基本的那个,不带上括号
public static int calculate(String s){
int res = 0;
int sign = 1;
int cur = 0;
for(int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if(Character.isDigit(c)){
cur = cur*10 + c-'0';
}else if(c == '+'){
res += sign * cur;
sign = 1;
cur = 0;
}else if(c == '-'){
res += sign * cur;
sign = -1;
cur = 0;
}
}
// 别忘了最后一个数
res += sign * cur;
return res;
}
// 带上括号,复杂了一点,避免重复遍历,把index设置成一个全局变量
public static int calculateII(String s, int[] index){
int res = 0;
int sign = 1;
int cur = 0;
for(; index[0] < s.length(); index[0]++){
char c = s.charAt(index[0]);
if(Character.isDigit(c)){
cur = cur * 10 + (c-'0');
}else if(c == '+'){
res += sign * cur;
sign = 1;
cur = 0;
}else if(c == '-'){
res += sign * cur;
sign = -1;
cur = 0;
}else if(c == '('){
index[0] ++;
int sub = calculateII(s, index);
System.out.println(sub);
res += sign * sub;
}else if(c == ')'){
// 注意最后一步
res += sign * cur;
return res;
}
}
// 注意最后一步
res += sign * cur;
return res;
}
}