用例
输入 | 输出 |
---|---|
“+2147483647” | 2147483647 |
“1a33” | 0 |
“-2147483648” | -2147483648 |
“123” | 123 |
Python 代码
# -*- coding:utf-8 -*-
class Solution:
def StrToInt(self, s):
# write code here
if s=='':
return 0
numlist=['0','1','2','3','4','5','6','7','8','9']
sum=0
flag2num = {'-':-1, '+': 1}
first = s[0]
flag = 1
if first in ['+', '-']: # 包含符号位的情况
flag = flag2num[first]
tmp = 0
for string in s[1:]:
if string in numlist:#如果是合法字符
sum=sum*10+numlist.index(string)
if string not in numlist:#非合法字符
sum=0
break#跳出循环
else:
for string in s[0:]:
if string in numlist:#如果是合法字符
sum=sum*10+numlist.index(string)
if string not in numlist:#非合法字符
sum=0
break#跳出循环
if -0x7fffffff-1<=sum*flag <= 0x7fffffff:
return sum*flag
else:
return 0
s = Solution()
res = s.myAtoi(" ")
print(res)