#7

Reverse Integer

Medium Overflow checks

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Reverse the digits of a 32-bit signed integer. If the reversed value doesn't fit in 32 bits, return 0. You may not use 64-bit integers.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: reverse the digits but return 0 if the answer doesn't fit in an int, and you can't use long to cheat.

Why this works: before adding a digit, compare the current result with MAX/10. If it's already bigger, the next step would overflow.

Example: x = -123

d = -3 → rev = -3d = -2 → rev = -32d = -1 → rev = -321

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Checking for overflow after the multiplication — by then the value has already wrapped around.