题目内容: 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.
注意以下要点:
- 字符串为空或者全是空格,返回0;
- 字符串的前缀空格忽略;
- (忽略空格之后)遇到的第一个字符,如果是‘+’或‘-’号,继续往后读,进入处理数字的阶段;如果第一个字符是数字,则进入处理数字的阶段;如果不是前面的2种,返回0;
- 处理数字的过程中,如果字符为非数字,就停止转换,返回当前值;
- 如果超过了int值的范围,那么返回 INT_MAX (2147483647) 或者 INT_MIN (-2147483648)。
Python
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
if not str:
return 0
str = str.strip()
sign = 1
if str[0] == "+" or str[0] == "-":
if len(str) == 1:
return 0
if not str[1].isdigit():
return 0
res = 0
for n in str:
if n == "-":
sign = -1
continue
if n == "+":
sign = 1
continue
if n.isdigit():
res = res * 10 + sign * (ord(n)-ord("0"))
else:
break
if res > 2147483647:
return 2147483647
elif res < -2147483648:
return -2147483648
else:
return res
C++
class Solution {
public:
int myAtoi(string str) {
if (str == "")
return 0;
int i = 0;
while (str[i] != '\0' && str[i] == ' ')
++i;
if (str[i] == '\0')
return 0; //空字符串
int sign = 1;
if (str[i] == '+')
{
sign = 1;
++i;
}
else if (str[i] == '-')
{
sign = -1;
++i;
} //正负号标记
long long sum = 0;
while (str[i] != '\0')
{
if (str[i] >= '0' && str[i] <= '9')
sum = sum * 10 + sign * (str[i] - '0');
else
return sum;
if (sum > INT_MAX || sum < INT_MIN)
return sum > 0 ? INT_MAX : INT_MIN; //溢出处理
++i;
}
return sum;
}
};