20min
from functools import reduce
# -*- coding:utf-8 -*-
class Solution:
def StrToInt(self, s):
return reduce(lambda x,y:x*10+y,map(lambda x:int(x),s)) #reduce函数的妙用
class Solution2:
def StrToInt(self, s):
flag=0
if not s :return 0
elif s[0]=='-' or s[0]=='+':flag=1
sum=0
for i in range(flag,len(s)):
if not s[i].isdigit():return 0 #isalnum,包括了字母
sum=sum*10+int(s[i])
return sum if s[0]!='-' else -sum
if __name__ == '__main__':
t=Solution2()
print(t.StrToInt('2147483647'))
print(t.StrToInt('+2147483647'))
print(t.StrToInt('-2147483647'))
print(t.StrToInt('1a33'))
print(t.StrToInt('a133'))
网友评论