-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring-to-integer-atoi
More file actions
35 lines (33 loc) · 895 Bytes
/
string-to-integer-atoi
File metadata and controls
35 lines (33 loc) · 895 Bytes
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
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
num = 0
sign = 0
started=0
for c in str:
if ord(c) > 47 and ord(c) < 58:
num = 10 * num + int(c)
started=1
elif (c) == ' ' and started==0:
continue
elif c == "-" and started == 0:
started=1
sign = -1
continue
elif c == "+" and started == 0:
sign = 1
started=1
continue
else:
break
num = int(num * (sign**sign))
if num < -2 ** 31:
return (-2 ** 31)
if num > 2 ** 31 - 1:
return (2 ** 31 - 1)
return num
if __name__ =="__main__":
print( Solution().myAtoi("+0 123"))