python3 integer inversion
Give you a 32-bit signed integer x, and return the result of inverting the digital part of x.
If the integer exceeds the 32-bit signed integer range [−2^31, 2^31 − 1] after the inversion, 0 is returned.
Assume that the environment does not allow storage of 64-bit integers (signed or unsigned).
Example 1:
Input: x = 123
Output: 321
Example 2:
Input: x = -123
Output: -321
Example 3:
Input: x = 120
Output: 21
Example 4:
Input: x = 0
Output: 0
Idea 1: Convert it to a string, flip it, and judge whether it is positive or negative. Finally, the title requires that if the inverted integer exceeds the range of 32-bit signed integers [−2^31, 2^31 − 1], 0 will be returned
class Solution:
def reverse(self, x: int) -> int:
str1 = str(x)
if str1[0] == '-':
str1 = str1[0] + str1[:0:-1]
else:
str1 = str1[::-1]
return int(str1) if -2147483648<int(str1)<2147483648 else 0
Idea 2: Do not use strings. When the flipped number is greater than the condition, it returns 0
class Solution:
def reverse(self, x: int) -> int:
y, res = abs(x), 0
# 则其数值范围为 [−2^31, 2^31 − 1]
boundry = (1<<31) -1 if x>0 else 1<<31
while y != 0:
res = res*10 +y%10
if res > boundry :
return 0
y //=10
return res if x >0 else -res
Improve:
class Solution:
def reverse(self, x: int) -> int:
str1 = str(x)
if str1[0] == '-':
str1 = str1[0] + str1[:0:-1]
a=int(str1)
if (1<<31)<abs(a):
return 0
else:
str1 = str1[::-1]
a= int(str1)
if a>(1<<31) -1:
return 0
return a