-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0008_String_to_Integer_atoi.py
More file actions
49 lines (43 loc) · 1.1 KB
/
0008_String_to_Integer_atoi.py
File metadata and controls
49 lines (43 loc) · 1.1 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
46
47
48
49
class Solution:
def myAtoi(self, s: str) -> int:
i = 0
N = len(s)
while i < N and s[i] == ' ':
i += 1
if i >= N:
return 0
if s[i] == '-':
negative = -1
i += 1
elif s[i] == '+':
negative = 1
i += 1
else:
negative = 1
while i < N and s[i] == '0':
i += 1
if i >= N or not ('0' < s[i] <= '9'):
return 0
stack = []
while i < N and '0' <= s[i] <= '9':
stack.append(ord(s[i]) - ord('0'))
i += 1
if not stack:
return 0
total = 0
i = 1
max_val = 2**31
while stack:
num = stack.pop()
total += i * num
if total >= max_val:
total = negative * max_val
if negative > 0:
total -= 1
return total
i *= 10
if total >= max_val:
total = max_val
if negative > 0:
total -= 1
return negative * total