Skip to content

Commit 748cb24

Browse files
authored
Update Solution.py
1 parent d62bc86 commit 748cb24

File tree

1 file changed

+15
-16
lines changed

1 file changed

+15
-16
lines changed

solution/0008.String to Integer(atoi)/Solution.py

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -5,22 +5,21 @@ def myAtoi(self, s):
55
:rtype: int
66
"""
77

8-
s = list(s.split()[0])
9-
Digits = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9}
10-
11-
if s[0] in "+-":
12-
Sign = 1 if s[0] == '+' else -1
8+
try:
9+
s = list(s.split()[0])
10+
Sign = {'+':1, '-':-1}[s[0]]
1311
s.pop(0)
14-
elif s[0] in Digits:
15-
Sign = 1
16-
else:
17-
return 0
18-
12+
except IndexError : return 0
13+
except KeyError: Sign = 1
14+
1915
Num = 0
2016
for i in s:
21-
if i == '.':
22-
break
23-
Num *= 10
24-
Num += Digits[i]
25-
26-
return Sign*Num
17+
try: Num = int(i) + (Num*10)
18+
except ValueError: break
19+
20+
Num = Sign*Num
21+
if Num > 2147483647:
22+
return 2147483647
23+
elif Num < -2147483648:
24+
return -2147483648
25+
return Num

0 commit comments

Comments
 (0)