# LeetCode 8 — String to Integer (atoi)（C++ Java Python）

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.

atoi的需求：

注意考虑特殊情况。

C++实现：

class Solution {
public:
int atoi(const char *str) {
if(str == NULL)
{
return 0;
}

int i = 0;
while(str[i] == ' ')
{
++i;
}

int sign = 1;
if(str[i] == '-')
{
sign = -1;
++i;
}
else if(str[i] == '+')
{
++i;
}

long long res = 0;
while(str[i] != '\0')
{
if(str[i] >= '0' && str[i] <= '9')
{
res = res * 10 + (str[i] - '0');

if(res > INT_MAX)
{
return sign == -1 ? INT_MIN : INT_MAX;
}
}
else
{
break;
}

++i;
}

return sign * res;
}
};

Java实现：

public class Solution {
public int atoi(String str) {
String s = str.trim();

if (s.length() == 0) {
return 0;
}

int INT_MAX = Integer.MAX_VALUE;
int INT_MIN = Integer.MIN_VALUE;

int sign = 1;
int res = 0;

int i = 0;
if (s.charAt(0) == '-') {
sign = -1;
++i;
} else if (s.charAt(0) == '+') {
++i;
}

for (; i < s.length(); ++i) {
char digit = s.charAt(i);
if (digit >= '0' && digit <= '9') {
if (res > INT_MAX / 10 || digit - '0' > INT_MAX - res * 10) {
return sign == -1 ? INT_MIN : INT_MAX;
}

res = res * 10 + (digit - '0');
} else {
break;
}
}

return sign * res;
}
}

Python实现1：

class Solution:
# @return an integer
def atoi(self, str):
s = str.strip()

if len(s) == 0:
return 0

INT_MAX, INT_MIN = 2147483647, -2147483648

sign = 1
if s[0] in '+-':
if s[0] == '-':
sign = -1
s = s[1:]

if s.isdigit():
res = int(s)
else:
i = 0
while s[i].isdigit():
i += 1
if i != 0:
s = s[0:i]
res = int(s)
else:
return 0

if res > INT_MAX:
return INT_MIN if sign == -1 else INT_MAX

return sign * res

Python实现2：

<pre code_snippet_id="199947" snippet_file_name="blog_20140222_4_5943964" name="code" class="python">class Solution:
# @return an integer
def atoi(self, str):
s = str.strip()

if len(s) == 0:
return 0

INT_MAX, INT_MIN = 2147483647, -2147483648

sign = 1
i = 0
if s[0] == '-':
sign = -1
i += 1
elif s[0] == '+':
i += 1

res = 0
while i < len(s):
digit = ord(s[i]) - ord('0')
if digit >= 0 and digit <= 9:
res = res * 10 + digit
if res > INT_MAX:
return INT_MIN if sign == -1 else INT_MAX
else:
break;

i += 1;

return sign * res

感谢阅读，欢迎评论！