forked from tanglu/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstringToInteger.java
36 lines (34 loc) · 1.04 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
public class Solution {
public int atoi(String str) {
int result = 0;
short sign = 1;
int i = 0;
boolean begin_num = false;
while(i<str.length()&&str.charAt(i)==' ') {
i++;
}
if(i<str.length()&&str.charAt(i)=='+'){
i++;
}
if(i<str.length()&&str.charAt(i)=='-'){
sign = -1;
i++;
}
while(i<str.length()) {
if(str.charAt(i)>'9'||str.charAt(i)<'0') {
break;
}
//should rember how to detect the overflow of Integer
if(result> Integer.MAX_VALUE/10 || (result==Integer.MAX_VALUE/10 && Integer.MAX_VALUE%10 < (str.charAt(i) - '0'))) {
if (sign==1)
return Integer.MAX_VALUE;
else
return Integer.MIN_VALUE;
}
result = result*10 + str.charAt(i) - '0';
i++;
}
result = result * sign;
return result;
}
}