table of Contents
Title description
Given a 32-bit signed integer, you need to invert the digits on each bit of the integer. For overflowing 32-bit numbers, 0 is returned.
Input/output description
enter | 321 |
Output | 123 |
solution
The topic is relatively simple, and you need to pay attention to two places:
- The number entered may be negative. Negative number is still negative after reversal
- If the inverted number exceeds 32 bits, it needs to return 0
Code
class Solution:
def reverse(self, x: int) -> int:
positive = True
if x < 0:
positive = False
x = -x
x = int(str(x)[::-1])
if not positive:
x = -x
if self.out_of_range(x):
return 0
else:
return x
@staticmethod
def out_of_range(x: int) -> bool:
return x > 2 ** 31 - 1 or x < -2 ** 31
Code walkthrough
class Solution: def reverse(self, x: int) -> int: # First judge the positive and negative of x. After recording, convert x into a positive number (convenient for reverse order) positive = True if x <0: positive = False x = -x # reverse order, and then restore x x = int(str(x)[: :-1]) if not positive: x = -x # Determine if x overflows 32 bits if self.out_of_range(x): return 0 else: return x @staticmethod def out_of_range(x: int) -> bool: return x> 2 ** 31-1 or x <-2 ** 31