File tree Expand file tree Collapse file tree 3 files changed +49
-0
lines changed Expand file tree Collapse file tree 3 files changed +49
-0
lines changed Original file line number Diff line number Diff line change 7070- [ 4 Median of Two Sorted Arrays] ( https://leetcode.com/problems/median-of-two-sorted-arrays/description/ )
7171- [ 5 Longest Palindromic Substring] ( https://leetcode.com/problems/longest-palindromic-substring/description/ )
7272- [ 6 Zigzag Conversion] ( https://leetcode.com/problems/zigzag-conversion/description/ )
73+ - [ 7 Reverse Integer] ( https://leetcode.com/problems/reverse-integer/description/ )
7374- [ 8 String to Integer (atoi)] ( https://leetcode.com/problems/string-to-integer-atoi/description/ )
7475- [ 9 Palindrome Number] ( https://leetcode.com/problems/palindrome-number/description/ )
7576- [ 11 Container With Most Water] ( https://leetcode.com/problems/container-with-most-water/description/ )
Original file line number Diff line number Diff line change 1+ class Solution :
2+ """Base class for all LeetCode Problems."""
3+
4+ def reverse (self , x : int ) -> int :
5+ """
6+ Given a signed 32-bit integer x, return x with its digits reversed. If reversing
7+ x causes the value to go outside the signed 32-bit integer range
8+ [-231, 231 - 1], then return 0.
9+
10+ Assume the environment does not allow you to store 64-bit integers
11+ (signed or unsigned).
12+ """
13+ # Time Complexity: O(n)
14+ # Space Complexity: O(1)
15+
16+ sign = "-" if x < 0 else "+"
17+ x = abs (x )
18+ result = 0
19+ while x != 0 :
20+ # Check if 32-bit integer
21+ if sign == "-" and result >= (2 ** 31 ) / 10 :
22+ return 0
23+ if sign == "+" and result >= (2 ** 31 - 1 ) / 10 :
24+ return 0
25+
26+ digit = x % 10
27+ result *= 10
28+ result += digit
29+ x = x // 10
30+
31+ return - result if sign == "-" else result
Original file line number Diff line number Diff line change 1+ import pytest
2+
3+ from awesome_python_leetcode ._7_reverse_integer import Solution
4+
5+
6+ @pytest .mark .parametrize (
7+ argnames = ["x" , "expected" ],
8+ argvalues = [
9+ (123 , 321 ),
10+ (- 123 , - 321 ),
11+ (120 , 21 ),
12+ ],
13+ )
14+ def test_func (x : int , expected : int ):
15+ """Tests the solution of a LeetCode problem."""
16+ reversed_x = Solution ().reverse (x )
17+ assert reversed_x == expected
You can’t perform that action at this time.
0 commit comments