您的位置:首页 > 其它

leetcode笔记--String to Integer (atoi)

2016-02-23 20:44 357 查看
题目:难度(Easy)

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.

Update (2015-02-10):

The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.

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.

Tags:Math String

Similar Problems:(E) Reverse Integer (H) Valid Number

分析:由题目可得到以下要求

1.串头部的空格字符全部忽略,从第一个非空白字付开始检查,然后从第一个非空白字符往后找到尽可能多的数字字符(直到遇到非数字字符就停止往后检查),然后为找到的数字添加相应的正负号

2.在形成数字的串后面,可以包含除了数字以外的其他字符,他们对转换没有影响

3.如果串里只有空白符或是空串,或者从串的非空白字符开始不能转化成一个整数,则不进行转化,则返回0

4.如果进行了有效转化,还要看转化后的整数是否溢出

MAXINT = 2147483647 10位数 pow(2, 31) - 1

MININT = -2147483648 10位数 -(pow(2, 31))

代码实现:

class Solution(object):
def myAtoi(self, s):
"""
:type s: str
:rtype: int
"""
MAXINT = 2147483647  10位数   pow(2, 31) - 1
MININT = -2147483648  10位数  -(pow(2, 31))
"""

strTest = s.lstrip()
if strTest == "":
return 0

#处理第一个非空白字符
if strTest[0] == '-':
sign = -1
strTest = strTest[1:]
elif strTest[0] == '+':
sign = 1
strTest = strTest[1:]
elif strTest[0].isdigit():
sign = 1
else:
#第一个非空白字符不是“+”、“-”号也不是数字字符
return 0

MAXINT = pow(2, 31) - 1
MININT = -pow(2, 31)
#strNum里存储digit字符
strNum = []
for digit in strTest:
if digit.isdigit():
strNum.append(digit)
else:
break

#处理完有效数字字符
numStrResult = "".join(strNum)
if len(numStrResult) > 0:
if len(numStrResult) < 10:
#不可能溢出
return sign * int(numStrResult)
elif len(numStrResult) == 10:
if numStrResult > str(MAXINT) and sign > 0:
return MAXINT
elif numStrResult > str(MAXINT+1) and sign < 0:
return MININT
else:
return sign * int(numStrResult)
else:
#len(numStrResult) > 10
if sign > 0:
return MAXINT
else:
return MININT
else:
return 0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: