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 theIf 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.
Python代码:
class Solution:
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
if (str == ""):
return 0
MAX = 0x7FFFFFFF
MIN = 0x80000000
length = len(str)
ret = 0
op = 1
p = 0
while (str[p] == ' ' and (p + 1) < length):
p += 1
if (str[p] == '+' or str[p] == '-'):
if (str[p] == '-'):
op = -1
p += 1
for i in range(p, length):
if ('0' <= str[i] and str[i] <= '9'):
ret = ret * 10 + int(str[i])
if (op == 1 and ret > MAX):
return MAX
if (op == -1 and ret > MIN):
return -MIN
else:
break
return int(ret * op)
总结:
- 空字符串返回0
- 全空格字符串返回0,此处需要注意边界
- 处理字符串前先去除空格
- 判断有无符号,最多只能允许一个符号
- 对每个字符乘以位的权值再加起来,就转换为相应的数值,此时要判断是否超出int的边界(0x7FFFFFFF 与 0x80000000),过界了就返回边界值
- 当字符串中出现非数字字符时即数字字符读取结束,退出循环(123 1,123x1都返回123)