-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringToInteger.py
More file actions
43 lines (40 loc) · 1.22 KB
/
StringToInteger.py
File metadata and controls
43 lines (40 loc) · 1.22 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
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
sign = 1
all_digits = []
number = ""
digit_flag = False
sign_flag = False
for char in str:
if char == " " and digit_flag:
break
elif char == " " and not sign_flag:
continue
if char == '-' and not sign_flag and not digit_flag:
sign *= -1
sign_flag = True
continue
if char == '+' and not sign_flag and not digit_flag:
sign = 1
sign_flag = True
continue
# print ord(char)
if not (ord(char) >= ord('0') and ord(char) <= ord('9')) and not digit_flag:
return 0
elif not (ord(char) >= ord('0') and ord(char) <= ord('9')):
break
else:
number += char
digit_flag = True
# print(number)
if number == "":
return 0
result = int(number) * sign
if result >= 0:
return min(result, 2 ** 31 - 1)
else:
return max(result, -2 ** 31)