Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
Solution:
public int reverse(int x) {
int result = 0;
int newResult;
int tail;
while (x != 0) {
tail = x % 10;
newResult = result * 10 + tail;
if (result != (newResult - tail) / 10) {
return 0;
}
result = newResult;
x = x / 10;
}
return result;
}