Reverse Integer
0 0
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
Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

About Author

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

Leave a Reply

Your email address will not be published. Required fields are marked *