forked from dimitar9/Algorithm_Collection
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathatoi.java
More file actions
25 lines (23 loc) · 829 Bytes
/
atoi.java
File metadata and controls
25 lines (23 loc) · 829 Bytes
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
//standard solution from leetcode.
private static final int maxDiv10 = Integer.MAX_VALUE / 10;
public int atoi(String str) {
int i = 0, n = str.length();
while (i < n && Character.isWhitespace(str.charAt(i))) i++;
int sign = 1;
if (i < n && str.charAt(i) == '+' ) {
i++;
} else if (i < n && str.charAt(i) == ' - ' ) {
sign = - 1;
i++;
}
int num = 0;
while (i < n && Character.isDigit(str.charAt(i))) {
int digit = Character.getNumericValue(str.charAt(i));
if (num > maxDiv10 || num == maxDiv10 && digit >= 8) {
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
num = num * 10 + digit;
i++;
}
return sign * num;
}