diff --git a/Python/8_string_to_integer_atoi/__pycache__/solution.cpython-312.pyc b/Python/8_string_to_integer_atoi/__pycache__/solution.cpython-312.pyc new file mode 100644 index 00000000..39837a4e Binary files /dev/null and b/Python/8_string_to_integer_atoi/__pycache__/solution.cpython-312.pyc differ diff --git a/Python/8_string_to_integer_atoi/__pycache__/test_solution.cpython-312-pytest-7.4.4.pyc b/Python/8_string_to_integer_atoi/__pycache__/test_solution.cpython-312-pytest-7.4.4.pyc new file mode 100644 index 00000000..640aceb0 Binary files /dev/null and b/Python/8_string_to_integer_atoi/__pycache__/test_solution.cpython-312-pytest-7.4.4.pyc differ diff --git a/Python/8_string_to_integer_atoi/solution.py b/Python/8_string_to_integer_atoi/solution.py new file mode 100644 index 00000000..f464aa4a --- /dev/null +++ b/Python/8_string_to_integer_atoi/solution.py @@ -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 \ No newline at end of file diff --git a/Python/8_string_to_integer_atoi/test_solution.py b/Python/8_string_to_integer_atoi/test_solution.py new file mode 100644 index 00000000..bce2be43 --- /dev/null +++ b/Python/8_string_to_integer_atoi/test_solution.py @@ -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 \ No newline at end of file