0%

String to Integer (atoi)

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

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
public int myAtoi(String str) {
if(str == null) return 0;
//清除字符串首尾空格
str = str.trim();
if(str.length() == 0) return 0;

boolean positive = true;
int index = 0;
long result = 0;

//确定符号位并向后扫描一位
if(str.charAt(index) == '-') {
++index;
positive = false;
} else if(str.charAt(index) == '+')
++index;

//从符号位向后扫描,注意result = result * 10 + (c - '0')
//这种字符串转数字的方法,这种方法只需要从前向后扫描一次
//每次只需要一次乘法和一次加法(不用分别计算结果和基)
while(index < str.length()) {
char c = str.charAt(index);
if(c >= '0' && c <= '9') {
result = result * 10 + (c - '0');
++index;
} else
//如果遇到非数字字符,提前退出循环
break;
//超出Integer表示范围时,返回边界值
if(positive && result >= Integer.MAX_VALUE) return Integer.MAX_VALUE;
if(!positive && (-result) < Integer.MIN_VALUE) return Integer.MIN_VALUE;
}
return positive ? (int) result : (int)(-result);
}