DSA Tracker

Visualize

Reverse Integer

time O(n)space O(1)

The key insight: any integer can be reversed digit by digit using modular arithmetic (x % 10 extracts the last digit) and integer division (Math.floor(x / 10) drops the last digit), building the reversed number by shifting existing digits left (result * 10) and adding the new digit. This avoids string conversion entirely and processes the number in a single left-to-right pass through its digits.

Details

Animated on: Given a signed 32-bit integer x, reverse its digits and return the reversed integer.

Problem:Reverse IntegerMedium

Math

step 1 / 10

123
[0]

reversed = 0. Seed the reversed accumulator; no digits have been processed yet.

  • x=0· arr[0] = 123
Pseudocode
1FUNCTION reverseInteger(x):
2 reversed = 0
3 WHILE x > 0:
4 digit = last digit of x (x mod 10)
5 reversed = reversed * 10 + digit
6 drop the last digit of x (integer divide x by 10)
7 RETURN reversed

← / → step · space play · Home restart

Every step in words

Show all 10 steps
  1. reversed = 0. Seed the reversed accumulator; no digits have been processed yet.
  2. digit = x % 10 = 123 % 10 = 3. Pop the last digit 3 from x using modular arithmetic.
  3. reversed = reversed * 10 + digit = 0 * 10 + 3 = 3. Shift left and add the first digit; reversed is now 3.
  4. x = Math.floor(x / 10) = Math.floor(123 / 10) = 12. Remove the last digit from x; x is now 12.
  5. digit = x % 10 = 12 % 10 = 2. Pop the next last digit 2 from x.
  6. reversed = reversed * 10 + digit = 3 * 10 + 2 = 32. Shift left and add digit 2; reversed is now 32.
  7. x = Math.floor(x / 10) = Math.floor(12 / 10) = 1. Remove the last digit; x is now 1.
  8. digit = x % 10 = 1 % 10 = 1. Pop the final last digit 1 from x.
  9. reversed = reversed * 10 + digit = 32 * 10 + 1 = 321. Shift left and add digit 1; reversed is now 321.
  10. x = Math.floor(x / 10) = Math.floor(1 / 10) = 0. x is now 0; loop exits. Return reversed = 321.

Now solve it yourself

Watching is the first half. The second is writing it without the animation.