-
Notifications
You must be signed in to change notification settings - Fork 0
/
leetcode8v2.java
32 lines (30 loc) · 891 Bytes
/
leetcode8v2.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
/*
Solution: consider overflow situation
Time: O(n)
*/
public class Solution {
private static final int maxDivTen = Integer.MAX_VALUE / 10;
public int myAtoi(String str) {
int i = 0;
int n = str.length();
int sign = 1;
while(i < n && Character.isWhitespace(str.charAt(i)))
i++;
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 > maxDivTen || num == maxDivTen && digit >= 8){
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
num = num * 10 + digit;
i++;
}
return sign * num;
}
}