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.
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
reversed = 0. Seed the reversed accumulator; no digits have been processed yet.
- x=0· arr[0] = 123
1FUNCTION reverseInteger(x):2 reversed = 03 WHILE x > 0:4 digit = last digit of x (x mod 10)5 reversed = reversed * 10 + digit6 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
- reversed = 0. Seed the reversed accumulator; no digits have been processed yet.
- digit = x % 10 = 123 % 10 = 3. Pop the last digit 3 from x using modular arithmetic.
- reversed = reversed * 10 + digit = 0 * 10 + 3 = 3. Shift left and add the first digit; reversed is now 3.
- x = Math.floor(x / 10) = Math.floor(123 / 10) = 12. Remove the last digit from x; x is now 12.
- digit = x % 10 = 12 % 10 = 2. Pop the next last digit 2 from x.
- reversed = reversed * 10 + digit = 3 * 10 + 2 = 32. Shift left and add digit 2; reversed is now 32.
- x = Math.floor(x / 10) = Math.floor(12 / 10) = 1. Remove the last digit; x is now 1.
- digit = x % 10 = 1 % 10 = 1. Pop the final last digit 1 from x.
- reversed = reversed * 10 + digit = 32 * 10 + 1 = 321. Shift left and add digit 1; reversed is now 321.
- 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.