Reverse the digits of an integer, preserving sign (e.g. 123 -> 321, -45 -> -54).
Repeatedly take the last digit with % 10 and build the reversed number as result = result * 10 + digit, dividing the input by 10 each step. Handle the sign separately or let it fall out of integer math. Watch for overflow when the reversed value exceeds the integer range.
public static int reverseInt(int n) {
long r = 0;
while (n != 0) { r = r * 10 + n % 10; n /= 10; }
if (r > Integer.MAX_VALUE || r < Integer.MIN_VALUE) return 0; // overflow
return (int) r;
}function reverseInt(n) {
const sign = Math.sign(n);
const r = parseInt(String(Math.abs(n)).split('').reverse().join(''), 10);
return r > 2147483647 ? 0 : sign * r;
}def reverse_int(n):
sign = -1 if n < 0 else 1
r = sign * int(str(abs(n))[::-1])
return r if -2**31 <= r <= 2**31 - 1 else 0Digit-by-digit manipulation appears in checksum/formatting logic, and the overflow guard is the boundary-value discipline testers prize.
Reversing 1,534,236,469 overflows a 32-bit int. How do you handle it?