The O(n) Club: Reverse Integer Without Getting Fired
⚡ TL;DR
Flip the digits of a 32-bit signed integer using only math—string hacks get you side-eye from every real interviewer. Oh, and watch for overflow like it’s a compliance audit. Here’s how a rookie might “solve” it (don’t do this in interviews):
// Weak: string conversion String s = Integer.toString(x); StringBuilder sb = new StringBuilder(s); int rev = Integer.parseInt(sb.reverse().toString());
🧠 How Devs Usually Mess This Up
🔍 What’s Actually Going On
Picture this: You’re a robot scooping coins from a pile, one at a time, and trying to stack them back in reverse without breaking the table. At every step, peek ahead—if stacking one more will break the pile (overflow), don’t. Java will absolutely let you fall off the edge, so be extra suspicious before slapping on that last coin (digit). The point: extract last digit, append to reversed result, check overflow first like a paranoid chef glancing at the oven every five minutes.
🛠️ PseudoCode
- Start with rev = 0;
Your fresh integer baby, still innocent. - While x isn’t zero:
- Pop digit:
int digit = x % 10;
- Check before you leap:
if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE/10 && digit > 7)) return 0;
if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE/10 && digit < -8)) return 0;
- Append:
rev = rev * 10 + digit;
- Chop off last digit:
x /= 10;
- Pop digit:
- Return rev. It’s ready. If you return 0, that’s because you saved the universe from integer overflow.
💻 The Code
public int reverse(int x) {
int rev = 0;
while (x != 0) {
int digit = x % 10;
if (rev > Integer.MAX_VALUE / 10 || (rev == Integer.MAX_VALUE / 10 && digit > 7)) return 0;
if (rev < Integer.MIN_VALUE / 10 || (rev == Integer.MIN_VALUE / 10 && digit < -8)) return 0;
rev = rev * 10 + digit;
x /= 10;
}
return rev;
}
⚠️ Pitfalls, Traps & Runtime Smacks
- Overflow quicksand: Try 1534236469 or the outer bounds. Fail to check before you add, and you’ll be debugging in the Upside Down.
- Funky negatives: -10? Yep, becomes -1. No leading zeros, no trailing drama.
- No digits: If x is zero, congrats, you get… zero. Even LeetCode won’t surprise you here.
- Time: O(number of digits)—fast enough unless you’re reversing your tax ID for fun.
- Space: No memory waste unless you consider int variables as RAM splurging.
🧠 Interviewer Brain-Tattoo
“Check for overflow before every multiply or add. Otherwise, you’re not reversing, you’re detonating.”