题目链接:
https://leetcode.com/problems/string-to-integer-atoi/
Implement atoi to
convert a string to an integer.
解题的很简单想法:
讲所给字符串转换为int()可识别的字符串。
然后改进了以下两种情况:
' -0012a42' >>> -12
'+1' >>> 1
耗时:58ms
(PS:走捷径使用int函数,果然速度快一些=-=!)
class Solution:
# @return an interger
def atoi(self, Str):
INT_MAX = 2147483647
INT_MIN = -2147483648
newstr = ''
i = 0
while (i<len(Str) and Str[i]==' '):
i += 1
if (i<len(Str) and (Str[i] == '-' or Str[i] == '+')):
newstr += Str[i]
i += 1
while (i<len(Str) and Str[i].isdigit()):
newstr += Str[i]
i += 1
try:
RES = int(newstr)
except:
RES = 0
if RES > INT_MAX:
RES = INT_MAX
if RES < INT_MIN:
RES = INT_MIN
return RES