All challenges
Easy 0 solved 0% acceptance

Reverse a Number

Reverse the decimal digits of a positive integer.

What you'll learn

  • Take digits off the end of a number one by one
  • Build a new number by shifting digits left (× 10)
  • Handle trailing zeros correctly

Problem

Write the decimal digits of n in reverse order and return the resulting number. Zeros that end up at the front disappear, so 1200 becomes 21.

Implement reverse_number(n).

Input

n: A positive integer.

Output

Return the reversed number.

Constraints

1 ≤ n ≤ 10¹⁸. The reversed value always fits a signed 64-bit integer.

Examples

Example 1
Input:
n = 352

Expected output:
expected = 253
Input:
long long n = 352;

Expected output:
long long expected = 253;
Input:
long n = 352;

Expected output:
long expected = 253;

Explanation

The digits 3, 5, 2 reversed are 2, 5, 3.

Example 2
Input:
n = 1200

Expected output:
expected = 21
Input:
long long n = 1200;

Expected output:
long long expected = 21;
Input:
long n = 1200;

Expected output:
long expected = 21;

Explanation

Reversed digits are 0021; leading zeros are dropped, giving 21.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

The key is to build the result one digit at a time from the end of the number.

Hint 2

Use repeated remainder and division to extract digits in reverse order.

Hint 3

Leading zeros in the reversed form should disappear naturally, so be careful not to preserve them.

Expected complexity

O(d) time, O(1) extra space

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.