BackendML

Reverse Integer

Medium2 min read
The Reverse Integer problem requires reversing the digits of a signed 32-bit integer.

Problem

Given a signed 32-bit integer x, return x with its digits reversed. If reversing the digits causes the result to fall outside the signed 32-bit integer range, return 0.

The 32-bit signed integer range is from -231 to 231 - 1.

Example(s)

Consider the following examples to understand the expected input and output.

Example 1

Input
x = 123
Output
321

Example 2

Input
x = -123
Output
-321

Solution

This solution uses the Math / Number Theory pattern. We extract the last digit using x % 10 and add it to reversed after shifting the existing digits one position to the left.

We use a long variable for the reversed number so that we can safely detect whether the result exceeds the 32-bit integer range before converting it back to int.
class Solution {
    public int reverse(int x) {
        long reversed = 0;

        while (x != 0) {
            int a = x % 10;

            // Add the last digit to the reversed number.
            reversed = reversed * 10 + a;

            // Remove the last digit from x.
            x = x / 10;
        }

        // Check if the reversed number exceeds the integer range.
        if (reversed > Integer.MAX_VALUE || reversed < Integer.MIN_VALUE) {
            return 0;
        }
        return (int) reversed;
    }
}

Complexity

We process each digit of the number once, so the time complexity is O(log x), where the number of digits determines the number of iterations.

The solution uses only a few variables, so the extra space complexity is O(1).

Comments

No comments yet. Ask a question or share what helped.