Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

 12 Input: 123 Output: 321 

Example 2:

 12 Input: -123 Output: -321 

Example 3:

 12 Input: 120 Output: 21 

Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [$−2^{31}$, $2^{31} − 1$]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Related Topics: Math

## 解題邏輯與實作

 123456789101112131415 class Solution: def reverse(self, x: int) -> int: if x == 0: return 0 is_negative = x < 0 x = x * -1 if is_negative else x str_x = str(x).strip('0') str_x = str_x[::-1] x = int(str_x) x = x * -1 if is_negative else x x = 0 if x < -2147483648 or x > 2147483647 else x return x 

 12345678910111213141516 class Solution: def reverse(self, x: int) -> int: if not x: return 0 is_negative = x < 0 x = x * -1 if is_negative else x result = 0 while x : result = result * 10 + x % 10 x //= 10 result = result * -1 if is_negative else result result = 0 if result < -2147483648 or result > 2147483647 else result return result