leetcode解题: String to Integer (8)

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:

这题要考虑的corner case比较多,也是这题的难点。
corner case有:
empty string
string with space
string with positive or negative sign
string with non-digit numbers
overflow integer
对于overflow的处理有两种情况。一个是当前的total乘以10之后超过Integer.MAX_VALUE,由于不能直接比total * 10 > Integer.MAX_VALUE, 我们可以换一种比法。
用Integer.MAX_VALUE / 10 < total 表示判断标准。
但是这又有一种情况就是Integer.MAX_VALUE / 10 是整数除法,可能会有遗漏的情况是最后一位不同。
那么就需要排除Integer.MAX_VALUE / 10 == total && Integer.MAX_VALUE % 10 < digit 的情况。
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
public class Solution {
public int myAtoi(String str) {
if (str == null || str.isEmpty() || str.trim().isEmpty()) {
return 0;
}
str = str.trim();
boolean isNegative = false;
if (str.charAt(0) == '-') {
isNegative = true;
str = str.substring(1);
} else if (str.charAt(0) == '+') {
str = str.substring(1);
}
// check if all characters are digits
int total = 0;
for (int i = 0; i < str.length(); ++i) {
char ch = str.charAt(i);
if (ch < '0' || ch >'9') {
break;
}
int digit = ch - '0';
if (Integer.MAX_VALUE/10 < total || (Integer.MAX_VALUE/10 == total && Integer.MAX_VALUE % 10 < digit)) {
return isNegative ? Integer.MIN_VALUE : Integer.MAX_VALUE;
}
total = total * 10 + digit;
}
return isNegative ? (-1) * total : total;
}
}