AlgoViz

Reverse a number

Easy

Pop digits off the back, push onto a new number

Problem

Given an integer n, return the number formed by reversing its digits.

In simple words

Peel digits off the end one by one and stack them onto a new number.

The idea

Take the last digit with n % 10, append it to the answer with rev = rev * 10 + digit, then drop it with n /= 10. Multiplying by 10 before adding is what shifts the digits already collected one place left.

The trick

  • `rev * 10 + d` is the append; do it before dividing n.
  • Watch for overflow on large inputs — 32-bit reversal is a classic trap.
  • Negatives: reverse the absolute value and reattach the sign.
1
2
3
4
0
1
2
3
rev0

Step 1 of 6. Reverse the digits of 1234. Start rev = 0. Values: 1, 2, 3, 4. rev 0.

1/6
Optimal
timeO(log n)spaceO(1)
1rev = 02while n > 0:3  d = n % 10           // last digit4  rev = rev * 10 + d5  n = n / 106return rev

Input

array
[1, 2, 3, 4]

Memory

d
left

Output

rev
0
answer

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Examples

Example 1

Input:
n = 123
Output:
321
Explanation:
Read the digits back to front: 3, 2, 1.

Example 2

Input:
n = 500
Output:
5
Explanation:
Reversing 500 gives 005, and leading zeros vanish, so 5.

Example 3

Input:
n = 7
Output:
7
Explanation:
A single digit reversed is itself.

Practice this problem:GeeksforGeeks(opens in a new tab)

Finished the walkthrough? Add it to your streak.