Visualize

Pattern visualizer

Reverse Integer

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. Animated on: Given a signed 32-bit integer x, reverse its digits and return the reversed integer..

Math

time O(n)space O(1)step 1 / 10
123
[0]
line 2

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

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

Where to practice Math