leetcode 8 String to Integer (atoi)
z

8. 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.


注意异常的输入:

“”
“acbd”
“+-123”
“ 111”
“0”
“ “
“+-+-“
“-1”
“ -0012a42”
“-11919730356x”
“999999999999999999999999999999”
“9223372036854775809”

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
 class Solution {
public int myAtoi(String str) {
// 判断是否是空的字符串
if (str.length() == 0){
return 0;
}
int index = 0;
int positive = 1;
long result = 0;
// 字符前面有可能存在空格,去掉
while(index < str.length() && str.charAt(index) == ' ' ){
index ++;
}
// 每一次index++操作后,要判断index是否已经超过数组范围
if (index == str.length()){
return 0;
}
// 一个正确的str刚开始的第一个数字应该是正负号
if(str.charAt(index) == '-' || str.charAt(index) == '+'){
positive = str.charAt(index)=='-'? -1:1 ;
index ++;
}
if (index == str.length()){
return 0;
}
while(index < str.length()){
// 判断是否是数字这一段应该放在whle里面,有可能存在一段数字后出现字母的情况
if (str.charAt(index) < '0' || str.charAt(index) > '9' ){
break;
}
result = result * 10 + str.charAt(index)-'0';
// 溢出的情况,虽然用了long型result,但是输入的数字可能造成long溢出,因此应该判断溢出应该放在while里面,而不能是while外。
if(result*positive > Integer.MAX_VALUE){
return Integer.MAX_VALUE;
}
if(result*positive < Integer.MIN_VALUE){
return Integer.MIN_VALUE;
}
index ++;
}
// 最后不要忘记乘上符号,返回的时候需要强制类型转换
result = result*positive;
return (int) result;
}
}

感觉我的答案还是不够简练,这里贴上discuss区里得分最高的solution:

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
public int myAtoi(String str) {
int index = 0, sign = 1, total = 0;
//1. Empty string
if(str.length() == 0) return 0;

//2. Remove Spaces
while(str.charAt(index) == ' ' && index < str.length())
index ++;

//3. Handle signs
if(str.charAt(index) == '+' || str.charAt(index) == '-'){
sign = str.charAt(index) == '+' ? 1 : -1;
index ++;
}

//4. Convert number and avoid overflow
while(index < str.length()){
int digit = str.charAt(index) - '0';
if(digit < 0 || digit > 9) break;

//check if total will be overflow after 10 times and add digit
if(Integer.MAX_VALUE/10 < total || Integer.MAX_VALUE/10 == total && Integer.MAX_VALUE %10 < digit)
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;

total = 10 * total + digit;
index ++;
}
return total * sign;
}