Leetcode#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.

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.

Requirements for atoi:
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.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

题目翻译

题目要求将字符串转换成整型数。类似于C++的atoi,不符合要求的返回-1,符合要求的返回0。

1.首先需要丢弃字符串前面的空格。

2.可能有正负号(注意只取一个,如果有多个正负号,那么说这个字符串是无法转换的,返回0。)

3.字符串可以包含0~9以外的字符,如果遇到非数字字符,那么只取该字符之前的部分,如“-00123a66”返回“-123”。

4.如果超出int的范围,返回边界值(2147483647或-2147483648)

思路

思路一

详解

见题目翻译。

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
public int myAtoi(String str) {

// 1.空字符串
if (str == null || str.length() == 0)
return 0;

// 2.去除空格
str.trim();

// 3. +/- 符号
boolean positive = true;
int i = 0;
if (str.charAt(0) == '+') {
i++;
} else if (str.charAt(0) == '-') {
positive = false;
i++;
}

// 4.计算真实的值
double tmp = 0;
for (; i < str.length(); i++) {
int digit = str.charAt(i) - '0';
if (digit < 0 || digit > 9)
break;

// 处理极值
if (positive) {
tmp = 10 * tmp + digit;
if (tmp > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
} else {
tmp = 10 * tmp - digit;
if (tmp < Integer.MIN_VALUE)
return Integer.MIN_VALUE;
}
}

int returnValue = (int) tmp;
return returnValue;
}