Reverse an Integer

Given an integer, compute and return its reverse form. This problem becomes a regular reversal problem if the integer is converted into a string to get its character array. This is very costly in terms of space and time. This problem can be computed in linear time in terms of the length of the integer by shifting an output integer to the left by 1 digit and adding the least significant digit to the output per iteration. Suppose given 1490132707, return 7072310941. The following traces out the computation. Note that the least significant digit is 7.

Example

# Given 1490132707
# Return 7072310941
#
# 1 707231094 * 10 + 1  = 7072310941
# 4 70723109 * 10 + 4   = 707231094
# 9 7072310 * 10 + 9    = 70723109
# 0 707231 * 10 + 0     = 7072310
# 1 70723 * 10 + 1      = 707231
# 3 7072 * 10 + 3       = 70723
# 2 707 * 10 + 2        = 7072
# 7 70 * 10 + 7         = 707
# 0 7 * 10 + 0          = 70
# 7 0 * 10 + 7          = 7

Implementation

public static int reverse(int x) {
    int sign = (x < 0) ? -1 : 1;
    int out = 0;

    x *= sign;

    while (x > 0) {
        out = out * 10 + (x % 10);
        x /= 10;
    }

    out *= sign;

    return out;
}

This article is my 25th oldest. It is 248 words long, and it’s got 0 comments for now.