-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path8.parseInt32.py
More file actions
50 lines (45 loc) · 1.3 KB
/
Copy path8.parseInt32.py
File metadata and controls
50 lines (45 loc) · 1.3 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
50
class Solution: # O(len(s))
def myAtoi(self, s):
"""
:type s: s
:rtype: int
"""
s = s.strip()
if not s:
return 0
j = -1
k = -1
start = False
neg = False
count = 0
for i in range(len(s)):
char_code = ord(s[i])
if char_code < ord('0') or char_code > ord('9'):
if start:
break
else:
if char_code == ord('+'):
count += 1
elif char_code == ord('-'):
count += 1
neg = not neg
else:
return 0
# logic required by the question: no more than one +-
if count > 1:
return 0
else:
if not start:
start = True
j = i
k = i
if j == -1: # only content symbols
return 0
result = int(s[j:k + 1]
if neg:
result = -result
if result > 2147483647:
return 2147483647
if result < -2147483648:
return -2147483648
return result