Skip to content

Commit 23bb3d6

Browse files
Merge pull request #10 from codewithme-py/feat/reverse-integer-0007
problem solution & test 0007
2 parents f6af2ef + 5bada5d commit 23bb3d6

2 files changed

Lines changed: 48 additions & 0 deletions

File tree

solutions/reverse_integer_0007.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution:
2+
def reverse(self, x: int) -> int:
3+
"""
4+
Reverse digits of an integer.
5+
Example 1:
6+
Input: x = 123
7+
Output: 321
8+
Example 2:
9+
Input: x = -123
10+
Output: -321
11+
Example 3:
12+
Input: x = 120
13+
Output: 21
14+
Note:
15+
Assume we are dealing with an environment which could only store
16+
integers within the 32-bit signed integer range: [−2^31, 2^31 − 1].
17+
For the purpose of this problem, assume that
18+
your function returns 0 when the reversed integer overflows.
19+
"""
20+
int_min, int_max, reversed_num = -2**31, 2**31 - 1, 0
21+
sign = 1 if x >= 0 else -1
22+
x_abs = abs(x)
23+
while x_abs:
24+
digit = x_abs % 10
25+
reversed_num = reversed_num * 10 + digit
26+
if sign * reversed_num < int_min or sign * reversed_num > int_max:
27+
return 0
28+
x_abs //= 10
29+
return sign * reversed_num

tests/test_reverse_integer_0007.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import pytest
2+
3+
from solutions.reverse_integer_0007 import Solution
4+
5+
6+
@pytest.mark.parametrize('args, expected', [
7+
(123, 321),
8+
(-123, -321),
9+
(120, 21),
10+
(0, 0),
11+
(1534236469, 0),
12+
(-2147483648, 0),
13+
(1563847412, 0),
14+
(1463847412, 2147483641),
15+
(1463847412, 2147483641),
16+
])
17+
def test_solution(args, expected):
18+
sol = Solution()
19+
assert sol.reverse(args) == expected

0 commit comments

Comments
 (0)