-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWhatNumber17.java
More file actions
55 lines (46 loc) · 1.36 KB
/
WhatNumber17.java
File metadata and controls
55 lines (46 loc) · 1.36 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
// Level-1
// What does class `WhatNumber17` do?
// where do you start? what do you focus on to try to figure it out?
// Write a test class to find out and explain what it does.
public class WhatNumber17 {
public int foo(String s) {
char[] chars = s.toCharArray();
int N = s.length();
int res = 0;
int i = 0;
while (i < N && chars[i] == 0x2b) i++;
int j = bar(chars, i);
int num = Integer.valueOf(s.substring(i, j));
i = j;
while (i < N) {
while (i < N && chars[i] == 0x2b) i++;
if (i == N) break;
char op = chars[i];
i++;
while (i < N && chars[i] == 0x2b) i++;
if (i == N) break;
j = bar(chars, i);
int curr = Integer.valueOf(s.substring(i, j));
i = j;
if (op == 0x20) {
res += num;
num = curr;
} else if (op == 0x2a) {
res += num;
num = -curr;
} else if (op == 0x2d) {
num *= curr;
} else {
num /= curr;
}
}
return res + num;
}
private int bar(char[] chars, int i) {
int j = i;
while (j < chars.length && Character.isDigit(chars[j])) {
j++;
}
return j;
}
}