Skip to content

Commit 4376570

Browse files
committed
problem solution & test 0008
1 parent f2b9fc2 commit 4376570

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution:
2+
def myAtoi(self, s: str) -> int:
3+
"""
4+
Skip leading spaces
5+
Check sign
6+
Convert digits
7+
Check overflow
8+
Return result
9+
"""
10+
flag, sign, result = 0, 1, 0
11+
space, plus, minus = ' ', '+', '-'
12+
INT_MAX, INT_MIN, OVERFLOW = 2**31 - 1, -2**31, 7
13+
length = len(s)
14+
while flag < length and s[flag] == space:
15+
flag += 1
16+
if flag < length and (s[flag] == plus or s[flag] == minus):
17+
sign = -1 if s[flag] == minus else 1
18+
flag += 1
19+
while flag < length and s[flag].isdigit():
20+
digit = ord(s[flag]) - ord('0')
21+
if result > INT_MAX // 10 or (result == INT_MAX // 10 and digit > OVERFLOW):
22+
return INT_MAX if sign == 1 else INT_MIN
23+
result = result * 10 + digit
24+
flag += 1
25+
return sign * result
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import pytest
2+
3+
from solutions.string_to_integer__atoi_0008 import Solution
4+
5+
6+
@pytest.mark.parametrize('args, expected', [
7+
('42', 42),
8+
(' -042', -42),
9+
('1337c0d3', 1337),
10+
('0-1', 0),
11+
('words and 987', 0),
12+
('-91283472332', -2147483648),
13+
('2147483648', 2147483647),
14+
('+-12', 0),
15+
(' + 413', 0),
16+
('4193 with words', 4193),
17+
('91283472332', 2147483647)
18+
])
19+
def test_solution(args: str, expected: int) -> None:
20+
sol = Solution()
21+
assert sol.myAtoi(args) == expected

0 commit comments

Comments
 (0)