ReverseInteger.java /** * 7. Reverse Integer * Reverse digits of an integer. * Example1: x = 123, return 321 * Example2: x = -123, return -321 * The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reve
/** * 7. Reverse Integer * Reverse digits of an integer. * Example1: x = 123, return 321 * Example2: x = -123, return -321 * The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows. * @param x * @return */ public static int reverseInteger(int x) { int devF = 1; int devR = 1; int base = 1; if (x < 0) { x = 0 - x; base = -1; } int tmp = x; while (tmp > 10) { tmp = tmp / 10; devF *= 10; } int result = 0; while (devF > 10) { int first = x / devF; int last = x % 10; result += (base*(last*devF+first*devR)); x = x- devF*first - devR*last; devF /=10; devR *=10; if(devF==10){ result += base*(x/devF)*devR; break; } } return result; }