An efficient way is to do it as shown below (similar to what you suggested).
public static long reverse(long x) {
long y = 0;
while(x > 0) {
y = y * 10 + x % 10;
x = x / 10;
}
return y;
}
This avoids expensive string conversions, does only one pass through the digits and does not use any memory (except for storing the result).
EDIT
A more efficient way, avoiding division and modulo operations is:
public static long reverse(int _x) {
long x = _x;
long y = 0;
while (x > 0) {
y = x + (y - ((x * 0x1999999Al) >> 32)) * 10; //y * 10 + x - (x/10) * 10;
x = ((x * 0x1999999Al) >> 32);
}
return y;
}
I also tried replacing multiplication by 10 using bitshift operations (x * 10 = (x << 3) + (x << 1)
) but it didn't seem to affect performance.
The top answer of this stackoverflow question shows how to divide fast by 10. For completeness, the answer provided states that it can be done as follows (credit to John Källén)
int32_t div10(int32_t dividend) {
int64_t invDivisor = 0x1999999A;
return (int32_t) ((invDivisor * dividend) >> 32);
}
This approach only allows to reverse an integer number (up to 2^31 - 1
). The result is a long, as 2^31 - 1 = 2147483647
and reverse(2147483647) = 7463847412 > 2^31 - 1
.
A fast way to perform a modulo 10 operation on x
is to divide and multiply it by 10, and then subtract that result from x
.