Algo-Sim › Math & Geometry

Reverse Integer

Medium · Math & Geometry · step through it in Java, Python and C++ on your own input

Reverse the digits of a 32-bit integer, returning 0 on overflow. Pop with % 10, push with × 10, and check the limit before every multiply.

Problem

Given a signed 32-bit integer x, return the integer formed by its digits in reverse order, keeping the sign. If that value falls outside [−2³¹, 2³¹ − 1], return 0. Assume the environment cannot hold 64-bit integers.

Constraints

Edge cases to test

Follow-up questions

How do you check overflow with only 32-bit ints?
Before rev × 10 + d, check rev > MAX / 10 or rev == MAX / 10 && d > 7 (and the mirror for negatives).
How does Java’s % handle negatives?
It keeps the sign of the dividend, so digits of a negative number are negative and the same loop works.

Solution

Java

public int reverse(int x) {
    int rev = 0;
    while (x != 0) {
        int digit = x % 10;
        x /= 10;
        if (rev > Integer.MAX_VALUE / 10 || (rev == Integer.MAX_VALUE / 10 && digit > 7)) {
            return 0;
        }
        if (rev < Integer.MIN_VALUE / 10 || (rev == Integer.MIN_VALUE / 10 && digit < -8)) {
            return 0;
        }
        rev = rev * 10 + digit;
    }
    return rev;
}

Python

def reverse(x):
    # Python ints never overflow, so check against 32-bit limits by hand.
    limit = (2**31 - 1) // 10
    rev = 0
    while x != 0:
        digit = x % 10 if x > 0 else -(-x % 10)
        x = (x - digit) // 10
        if rev > limit or (rev == limit and digit > 7):
            return 0
        if rev < -limit or (rev == -limit and digit < -8):
            return 0
        rev = rev * 10 + digit
    return rev

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int reverse(int x) {
        int rev = 0;
        while (x != 0) {
            int digit = x % 10;
            x /= 10;
            if (rev > INT_MAX / 10 || (rev == INT_MAX / 10 && digit > 7)) {
                return 0;
            }
            if (rev < INT_MIN / 10 || (rev == INT_MIN / 10 && digit < -8)) {
                return 0;
            }
            rev = rev * 10 + digit;
        }
        return rev;
    }
};

More Math & Geometry problems