Leetcode – 7. Reverse Integer

Problem

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).

Example 1:

Input: x = 123
Output: 321

Example 2:

Input: x = -123
Output: -321

Example 3:

Input: x = 120
Output: 21

Constraints:

  • -231 <= x <= 231 - 1

Solution

Convert to string

Naive solution: convert x to string, reverse then convert back to int

    def reverse(self, x: int) -> int:
        s = str(abs(x))
        s = s[::-1]
        if x > 0 and int(s) > (2 ** 31 - 1):
            return 0
        
        if x < 0 and int(s) > 2 ** 31:
            return 0

        return int(s) if x > 0 else int(s) * -1

Remainder method

class Solution:
    def reverse(self, x: int) -> int:
        result = 0
        max = 2 ** 31 - 1
        sign = - 1 if x < 0 else 1
        x = abs(x)

        while x != 0:
            x, r = divmod(x, 10)
            if result > (max / 10) or (result == max // 10 and r > max % 10) :
                result = 0
                break
            result = result * 10 + r

        return result * sign
Leave a Reply 0

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