Reverse Integer
2023-11-27T05:56:36 - Vicky Chhetri
Read Time:53 Second
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
Example 1:Input: x = 123 Output: 321
Example 2:Input: x = -123 Output: -321
Example 3:Input: x = 120 Output: 21
Solution 1
class Solution:
def reverse(self, x: int) -> int:
it_max= 2**31 - 1
it_min= -2**31
rev=0
sign=1
if x<0:
sign=-1
else:
sign=1
x=abs(x)
rev= int(str(x)[::-1])*sign
if rev >it_max:
return 0
if rev <it_min:
return 0
return rev
Solution 2
class Solution:
def reverse(self, x: int) -> int:
it_max= 2**31 - 1
it_min= -2**31
rev=0
sign=1
if x<0:
sign=-1
else:
sign=1
x=abs(x)
while x>0:
z= x%10
rev= rev*10+z
x=x//10
if rev >it_max:
return 0
if rev <it_min:
return 0
return rev*sign