forked from yuduozhou/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathStringToInteger.java
53 lines (52 loc) · 1.39 KB
/
StringToInteger.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
public class Solution {
public int atoi(String str) {
// Start typing your Java solution below
// DO NOT write main() function
if (str.length() < 1) return 0;
boolean neg = false;
boolean overflow = false;
int result = 0;
int i = 0;
while (i < str.length()){
char c = str.charAt(i);
if (Character.isWhitespace(c)){
i ++;
}
else if(c == '-' || c == '+' || Character.isDigit(c)){
break;
}
else{
return 0;
}
}
if (str.charAt(i) == '-'){
neg = true;
i ++;
}
else if (str.charAt(i) == '+'){
i ++;
}
while (i < str.length()){
char c = str.charAt(i);
if (Character.isDigit(c)){
int x = Character.digit(c, 10);
if ((Integer.MAX_VALUE - x)/10 >= result){
result = result * 10 + x;
i ++;
}
else{
overflow = true;
break;
}
}
else{
break;
}
}
if (overflow){
if (neg) return Integer.MIN_VALUE;
return Integer.MAX_VALUE;
}
return (neg) ? -result : result;
}
}