-
Notifications
You must be signed in to change notification settings - Fork 0
/
Atoi.java
63 lines (51 loc) · 1.73 KB
/
Atoi.java
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
import java.util.*;
class Atoi {
public static void main(String[] args) {
System.out.println(myAtoi("+1"));
}
public int myAtoi1(String s) {
s = s.trim();
if (s.isEmpty()) {
return 0;
}
int ans = 0, i = 0;
boolean neg = s.charAt(0) == '-';
boolean pos = s.charAt(0) == '+';
if (neg || pos) {
i++;
}
while (i < s.length() && Character.isDigit(s.charAt(i))) {
int digit = s.charAt(i) - '0';
if (ans > Integer.MAX_VALUE / 10 || (ans == Integer.MAX_VALUE / 10 && digit > Integer.MAX_VALUE % 10)) {
return neg ? Integer.MIN_VALUE : Integer.MAX_VALUE;
}
ans = ans * 10 + digit;
i++;
}
return neg ? -ans : ans;
}
public static int myAtoi(String s) {
int total = 0, sign = 1, digit = 0;
s = s.trim();
if (s.length() > 0) {
int i = 0;
if (s.charAt(0) == '-' || s.charAt(0) == '+') {
sign = s.charAt(0) == '+' ? 1 : -1;
i++;
}
for (int j = i; j < s.length(); j++) {
if (Character.isDigit(s.charAt(j))) {
digit = s.charAt(j) - '0';
} else {
break;
}
//check if total will be overflow after 10 times and add digit
if (Integer.MAX_VALUE / 10 < total || Integer.MAX_VALUE / 10 == total && Integer.MAX_VALUE % 10 < digit)
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
total = 10 * total + digit;
}
total = total * sign;
}
return total;
}
}