← Back to libraryQuestion 73 of 273
⌨️Java CodingIntermediate

Reverse an Integer

📌 Definition:

Reverse the digits of an integer, preserving sign (e.g. 123 -> 321, -45 -> -54).

📖 Detailed Explanation:

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.

💻 Solutions:
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 0
🔑 Key Points:
  • Extract digits with %10 and /10
  • result = result*10 + digit
  • Preserve the sign
  • Guard against overflow of the reversed value
🌍 Real-World Example:

Digit-by-digit manipulation appears in checksum/formatting logic, and the overflow guard is the boundary-value discipline testers prize.

🎯 Scenario-Based Interview Question:

Reversing 1,534,236,469 overflows a 32-bit int. How do you handle it?