Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file not shown.
Binary file not shown.
28 changes: 28 additions & 0 deletions Python/8_string_to_integer_atoi/solution.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
def my_atoi(s: str) -> int:
if not s:
return 0

i, n = 0, len(s)
INT_MAX = 2**31 - 1
INT_MIN = -2**31

while i < n and s[i] == ' ':
i += 1

sign = 1
if i < n and s[i] in ['+', '-']:
if s[i] == '-':
sign = -1
i += 1

result = 0
while i < n and '0' <= s[i] <= '9':
digit = ord(s[i]) - ord('0')

if result > INT_MAX // 10 or (result == INT_MAX // 10 and digit > 7):
return INT_MAX if sign == 1 else INT_MIN

result = result * 10 + digit
i += 1

return result * sign
19 changes: 19 additions & 0 deletions Python/8_string_to_integer_atoi/test_solution.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# test_solution.py
from solution import my_atoi

def test_simple_positive_number():
assert my_atoi("42") == 42

def test_handles_whitespace_and_negative_sign():
assert my_atoi(" -42") == -42

def test_stops_at_non_digit_characters():
assert my_atoi("4193 with words") == 4193

def test_clamps_to_max_int_on_overflow():
INT_MAX = 2**31 - 1
assert my_atoi("2147483648") == INT_MAX

def test_clamps_to_min_int_on_underflow():
INT_MIN = -2**31
assert my_atoi("-2147483649") == INT_MIN