-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path8_StringToInteger.py
More file actions
45 lines (44 loc) · 1.32 KB
/
8_StringToInteger.py
File metadata and controls
45 lines (44 loc) · 1.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Solution:
# @param {string} str
# @return {integer}
def myAtoi(self, str):
positive = True
signAllowed = True
spaceAllowed = True
value = 0
for ch in str:
if ch == ' ':
if spaceAllowed:
continue
else:
break
elif ch == '+':
if signAllowed:
spaceAllowed = False
signAllowed = False
else:
return 0
elif ch == '-':
if signAllowed:
spaceAllowed = False
signAllowed = False
positive = False
else:
return 0
elif ch in "0123456789":
spaceAllowed = False
digit = ord(ch) - ord('0')
if value > 214748364 or (value == 214748364 and digit > 7):
if positive:
return 2147483647
else:
return -2147483648
value = value * 10 + digit
else:
break
if not positive:
value = value * -1
return value
if __name__ == "__main__":
sol = Solution()
print sol.myAtoi("-123") == -123