8.字符串转换整数(atoi)

解题思路:

  1. 主要在于判断数值是否溢出,使用result>(Integer.MAX_VALUE-digit)/10来判断溢出
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
class Solution {
public int myAtoi(String str) {
char[] chars = str.toCharArray();
int len = chars.length;
if (len == 0) {
return 0;
}
int index = 0;
while (index < len && chars[index] == ' ') {
index++;
}
if (index == len) {
return 0;
}
boolean negative = false;
if (chars[index] == '-') {
negative = true;
index++;
} else if (chars[index] == '+') {
index++;
} else if (!Character.isDigit(chars[index])) {
return 0;
}
int result = 0;
while (index < len && Character.isDigit(chars[index])) {
int digit = chars[index] - '0';
if (result > (Integer.MAX_VALUE - digit) / 10) {
return negative ? Integer.MIN_VALUE : Integer.MAX_VALUE;
}
result = result * 10 + digit;
index++;
}
return negative ? -result : result;
}
}