Reverse Digits of a Number

80.1k
0

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

If the number ends with zeroes, those zeroes disappear in the reversed value because a number does not keep leading zeroes.

Example 1

Input: n = 12345

Output: 54321

Explanation: The digits are read from right to left, so 12345 becomes 54321.

Example 2

Input: n = -1200

Output: -21

Explanation: First reverse the digits of 1200, which gives 21, and then keep the negative sign.

Brute Force Approach

The first observation is that the last digit of a number can be taken out very easily using % 10.

For example, if the number is 1234, the last digit is 4. After taking it out, the remaining number becomes 123. Then the next last digit is 3, and this keeps going until no digits are left.

That gives the natural idea: keep picking the last digit and attach it to a new number from the right side. To attach a new digit properly, first shift the current reversed number one place left by multiplying it by 10, then add the new digit.

Algorithm

  • If N is negative, remember that sign first, because the digits should be reversed without changing their order logic.

  • Work with the absolute value of the number so digit extraction becomes simple and clean.

  • Keep a variable revNum as 0. This variable will store the reversed number as it is built.

  • While the current number is greater than 0, take its last digit using % 10.

  • Shift revNum one place left by multiplying it by 10, then add the extracted digit so that digit becomes the new last digit of the reversed number.

  • Remove the last digit from the current number using integer division by 10, because that digit has already been used.

  • After the loop finishes, put the original sign back on the reversed number.

Key Points

  • If N = 0, the reversed number is also 0.

  • Trailing zeroes in the original number disappear after reversal. For example, 1200 becomes 21.

  • If negative numbers are part of the problem, reverse the digits and keep the sign separately.

Dry Run

Reverse a Number Dry Run

Reverse a Number Dry Run

Solution

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
/*
Returns the number formed by
reversing the digits of n.
*/
long long reverseNumber(int n) {
// Stores whether the original number was negative.
bool isNegative = (n < 0);
// Uses the absolute value so digit extraction stays simple.
long long num = llabs((long long)n);
// Stores the reversed number as digits are appended one by one.
long long revNum = 0;
// Keep going until every digit has been taken from num.
while (num > 0) {
// Extract the current last digit of the number.
long long digit = num % 10;
// Shift the current answer left and place the new digit at the end.
revNum = revNum * 10 + digit;
// Remove the digit that has already been used.
num /= 10;
}
// Put the negative sign back only if the original number was negative.
if (isNegative) {
return -revNum;
}
return revNum;
}
};
// Driver code starts
int main() {
int n = -1200;
Solution obj;
cout << obj.reverseNumber(n) << endl;
return 0;
}

Complexity Analysis

Time Complexity: O(log10 N), because one digit is processed in each iteration.

Space Complexity: O(1), because only a few variables are used.

Optimal Approach

A number like 1234 can naturally be treated as a string "1234". The key observation is that reversing a number is exactly the same as reversing its string representation:

1234 → "1234" → "4321" → 4321

So instead of manually extracting digits using % 10 and / 10, we can let string operations handle the reversal.

Algorithm

  • Convert the number to a string

    • We use to_string(n) because reversing characters is simpler than repeatedly extracting digits.

  • Reverse the string

    • reverse(s.begin(), s.end())

    • After this, the digits are in the required reverse order.

  • Convert the reversed string back to an integer

    • Use stoi(s) because the final answer needs to be a number, not a string.

Dry Run

Reverse a Number Optimal Dry Run

Reverse a Number Optimal Dry Run

Solution

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
// Reverses the digits of a given number using string conversion.
int reverseNumber(int n) {
// Track whether the original number is negative.
bool isNegative = n < 0;
// Convert the absolute value to string to avoid reversing the minus sign.
string s = to_string(abs(n));
// Reverse the characters of the string.
reverse(s.begin(), s.end());
// Convert the reversed string back to an integer.
// stoi() automatically removes leading zeroes.
int reversed = stoi(s);
// Restore the negative sign if the original number was negative.
return isNegative ? -reversed : reversed;
}
};
// Driver code starts here
int main() {
int n = 12340;
Solution sol;
cout << "Reversed number: " << sol.reverseNumber(n) << endl;
return 0;
}

Complexity Analysis

Time Complexity: O(d) where d is the number of digits since each digit is processed only twice.

Space Complexity: O(d) for the string created using to_string.

Interview follow-up Questions

Numbers do not keep leading zeroes. After reversal, the digits would look like 0021, which is simply written as 21.

GreedyMathsIntroduction to DSA

Read Similar Blogs

Comments0