Skip to content

Commit 228edae

Browse files
committed
Sync LeetCode submission Runtime - 4 ms (16.12%), Memory - 17.9 MB (18.55%)
1 parent d9ee24c commit 228edae

File tree

2 files changed

+16
-9
lines changed

2 files changed

+16
-9
lines changed

0008-string-to-integer-atoi/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
<ol>
66
<li><strong>Whitespace</strong>: Ignore any leading whitespace (<code>&quot; &quot;</code>).</li>
7-
<li><strong>Signedness</strong>: Determine the sign by checking if the next character is <code>&#39;-&#39;</code> or <code>&#39;+&#39;</code>, assuming positivity is neither present.</li>
7+
<li><strong>Signedness</strong>: Determine the sign by checking if the next character is <code>&#39;-&#39;</code> or <code>&#39;+&#39;</code>, assuming positivity if neither present.</li>
88
<li><strong>Conversion</strong>: Read the integer by skipping leading zeros&nbsp;until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0.</li>
99
<li><strong>Rounding</strong>: If the integer is out of the 32-bit signed integer range <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code>, then round the integer to remain in the range. Specifically, integers less than <code>-2<sup>31</sup></code> should be rounded to <code>-2<sup>31</sup></code>, and integers greater than <code>2<sup>31</sup> - 1</code> should be rounded to <code>2<sup>31</sup> - 1</code>.</li>
1010
</ol>
Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,35 @@
1-
# Time: O(N)
1+
# Time: O(n)
2+
# Space: O(n)
23

34
class Solution:
45
def myAtoi(self, s: str) -> int:
56
sign, result = 1, 0
7+
8+
# Whitespace
69
s = s.lstrip()
7-
10+
811
if not s:
912
return 0
10-
13+
1114
idx = 0
12-
15+
16+
# Signedness
1317
if s[idx] == '-':
1418
sign = -1
1519
idx += 1
1620
elif s[idx] == '+':
1721
idx += 1
18-
22+
23+
# Conversion
1924
int_str = ''
2025
for i in range(idx, len(s)):
2126
if s[i].isdigit():
2227
int_str += s[i]
2328
else:
2429
break
25-
30+
2631
result = sign * int(int_str) if int_str else 0
27-
28-
return max(min(result, 2**31 - 1), -1 * 2**31)
32+
33+
# Rounding
34+
return max(min(result, 2 ** 31 - 1), -1 * 2 ** 31)
35+

0 commit comments

Comments
 (0)