string to integer

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 myAtoi(String str){
int index = 0;
int len = str.length();
int sign = 1;
int total = 0;
//排除String为空的情况
if(len == 0)
return 0;
//排除String开始为空字符的情况
while(str.charAt(index) == ' ')
index++;
//确定首个非空字符正负符号
if(str.charAt(index) == '+' || str.charAt(index) == '-'){}
sign = str.charAt(index) == '+' ? 1 : -1;
index++;
}
//reverse
while(index < len ){
int digit = str.charAt(index) - '0';
if(digit < 0 || digit > 9)
break;
//检查是否有溢出情况,要记住这种巧妙地方法
if(total > Integer.MAX_VALUE / 10 || total == Integer.MAX_VALUE / 10 && digit > Integer.MAX_VALUE % 10)
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
total = total*10 + digit;
index++;
}
return total*sign;
}
}