leetcode-8-java

问题8:String to Integer (atoi)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Implement atoi which converts a string to an integer.

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

Example 1:

Input: "42"
Output: 42
Example 2:

Input: " -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign.
Then take as many numerical digits as possible, which gets 42.

leetcode地址

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
46
47
/**
* 1.判断首字符是否是符号, 获取迭代的起始位置
* 2.判断是否是负号
* 3.上次迭代的结果数乘以10 然后加上 对应字符数字乘以符号基础数(1 or -1)
*
* @param str
* @return
*/
public static int myAtoi(String str) {
if (null == str ) {
return 0;
}
str = str.trim();
if (str.length() == 0) {
return 0;
}
char firstChar = str.charAt(0);
//是否符号
boolean isSign = false;
//是否负号
boolean isNeg = false;
if ((isNeg = ('-' == firstChar)) || '+' == firstChar) {
isSign = true;
}


long result = 0;
//起始位置
int index = isSign ? 1 : 0;
//基础数
int neg = isNeg ? -1 : 1;
char[] chars = str.toCharArray();
for (int i = index; i < chars.length; i++) {
char tmp = chars[i];
if (tmp < 48 || tmp > 57) {
break;
}
result = result * 10 + Long.valueOf(String.valueOf(tmp)) * neg;
if (result > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
if (result < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
}
return (int) result;
}