Leetcode Reverse Integer Python Solution

Leetcode Question

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.

Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

Python Solution

class Solution:
    def reverse(self, x: int) -> int:
        MAX_INT = 2**31-1
        MIN_INT = -2**31
        result = 0
        while x!=0:
            if result>MAX_INT/10 or result<MIN_INT/10:
                return 0
            digit = x%10 if x>0 else x%-10
            #print('digit:',digit)
            x = math.trunc(x/10)
            #print('x:',x)
            result = result*10 + digit
        return result

Cracking the Coding Interview: 189 Programming Questions and Solutions

Unknown's avatar

Author: mathtuition88

Math and Education Blog

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.