-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyAtoi.java
More file actions
69 lines (53 loc) · 1.45 KB
/
Copy pathMyAtoi.java
File metadata and controls
69 lines (53 loc) · 1.45 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
package org.example;
public class MyAtoi {
public int myAtoi(String s) {
if (s == null || s.isEmpty()) {
return 0;
}
int curr = 0;
while (curr < s.length() && s.charAt(curr) == ' ') {
curr++;
}
if (curr == s.length()) {
return 0;
}
int sign = 1;
if (s.charAt(curr) == '-') {
sign = -1;
curr++;
} else if (s.charAt(curr) == '+') {
curr++;
}
while (curr < s.length() && s.charAt(curr) == '0') {
curr++;
}
long sum = 0;
for (int i = curr; i < s.length(); i++) {
char c = s.charAt(i);
if (isDigit(c)) {
sum = sum * 10 + (c-'0');
if (sign == 1 && sum > Integer.MAX_VALUE ) {
break;
}
if (sign == -1 && sum > (long)Integer.MAX_VALUE + 1) {
break;
}
} else {
break;
}
}
if (sign > 0 && sum > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
} else if (sign < 0 && sum > (long)Integer.MAX_VALUE + 1) {
return Integer.MIN_VALUE;
} else {
return (int) (sum * sign);
}
}
private boolean isDigit(char c) {
if (c >= '0' && c <= '9') {
return true;
}
return false;
}
}