1
# Runtime: 69 ms (Top 20.00%) | Memory: 13.9 MB (Top 79.88%)
2

3

4
class Solution:
5

6
def assign_sign(self, sign):
7
# verify that we haven't already got a sign
8
#  "+42-" -> we don't want to return -42; hence check
9
if not self.is_neg and not self.is_pos:
10
# no sign has been set yet
11
if sign == "+":
12
self.is_pos = True
13
elif sign == "-":
14
self.is_neg = True
15
return
16

17
def add_to_int(self, num):
18
if not self.num:
19
self.num = num
20
else:
21
self.num = (self.num * 10) + num
22

23
def myAtoi(self, s: str) -> int:
24
#  remove the leading and trailing spaces
25
self.is_neg = False
26
self.is_pos = False
27
self.num = None
28
s = s.strip()
29
for i in s:
30
# ignore the rest of the string if a non digit character is read
31
if i in ("+", "-"):
32
#  only read the first symbol; break if second symbol is read
33
if self.is_pos or self.is_neg or isinstance(self.num, int):
34
#  one of the two symbols is read or a number is read
35
break
36
self.assign_sign(i)
37
continue
38
try:
39
i = int(i)
40
self.add_to_int(i)
41
except ValueError:
42
# it's neither a sign, nor a number; terminate
43
break
44

45
# outside the loop; compile the result
46
if not self.num:
47
return 0
48
upper_limit = 2**31 - 1
49
if self.is_pos or (not self.is_pos and not self.is_neg):
50
if self.num > upper_limit:
51
self.num = upper_limit
52
elif self.is_neg:
53
if self.num > upper_limit + 1:
54
self.num = upper_limit + 1
55
self.num = -1 * self.num
56
return self.num

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0