Back to C++
2025-12-115 min read

Reverse a Number

Learn Reverse a Number step by step with clear examples and exercises.

Why This Matters

Reversing a number is an essential programming skill that comes up frequently in coding interviews, competitive programming, and real-world software development. It can help you solve problems like palindrome detection, data encoding, and debugging issues caused by incorrect input order. Additionally, understanding the concept of reversing a number will provide a foundation for more advanced topics such as big integer arithmetic and number theory.

Prerequisites

To understand the concept of reversing a number in C++, you should already be familiar with:

  1. Basic C++ syntax (variables, operators, control structures)
  2. Understanding of data types like int, char, and arrays
  3. Knowledge of standard input/output functions such as cin and cout
  4. Familiarity with basic algorithms and problem-solving techniques
  5. Understanding of recursion and iteration concepts
  6. Basic understanding of bitwise operations (optional but helpful)

Core Concept

A simple way to reverse a number is by converting it into a string, reversing the string, and then converting it back into a number. However, this method can be slow and wasteful for large numbers. A more efficient approach is to use recursion or iteration to manipulate the digits directly.

Iterative Method

Here's an iterative method to reverse a number:

#include <iostream>
using namespace std;

void reverse(int num, int reversedNum = 0) {
// Base case: if num is 0, return the reversed number
if (num == 0) {
cout << reversedNum << endl;
return;
}

// Get the last digit of the number and add it to the reversed number
int lastDigit = num % 10;
reversedNum = reversedNum * 10 + lastDigit;

// Remove the last digit from the number and continue the process recursively
reverse(num / 10, reversedNum);
}

int main() {
int num;
cout << "Enter a positive integer: ";
cin >> num;

reverse(num); // Call the reverse function with the input number
return 0;
}

In this code, we define a recursive function reverse that takes an integer num and reverses it. The base case is when num becomes 0, at which point we print the reversed number. Otherwise, we calculate the last digit of the number using the modulus operator (%), add it to the reversed number, and remove the last digit by dividing num by 10. We then call the reverse function recursively with the updated num.

Recursive Method

Here's a recursive method for reversing a number:

#include <iostream>
using namespace std;

void reverse(int num, int reversedNum = 0) {
// Base case: if num is 0, return the reversed number
if (num == 0) {
cout << reversedNum << endl;
return;
}

// Get the last digit of the number and add it to the reversed number
int lastDigit = num % 10;
reverse(num / 10, reversedNum * 10 + lastDigit);
}

int main() {
int num;
cout << "Enter a positive integer: ";
cin >> num;

reverse(num); // Call the reverse function with the input number
return 0;
}

This code is similar to the iterative method, but instead of using multiplication and addition to build the reversed number, we pass the updated reversedNum as an argument in the recursive call. The base case remains the same: when num becomes 0, we print the reversed number.

Worked Example

Let's reverse the number 12345 using both methods:

Iterative Method:

reverse(12345); // Output: 54321

Recursive Method:

reverse(12345); // Output: 54321

Both methods produce the correct output, demonstrating that they are working as intended.

Common Mistakes

  1. Not handling negative numbers: When dealing with negative numbers, you may need to consider their absolute value and then apply the reversal process.
void reverse(int num) {
if (num < 0) {
cout << "-";
num = -num;
}
// ... (rest of the code remains the same)
}
  1. Forgetting to handle zero: The base case should account for both positive and negative zeros (0 and -0).
void reverse(int num) {
if (num == 0) {
cout << "0";
return;
}
// ... (rest of the code remains the same)
}
  1. Using the wrong data types: Be careful when using long long or other data types to store large numbers to avoid overflow errors.
  2. Not handling very large numbers: For extremely large numbers, you may need to use libraries like GMP (GNU Multiple Precision Arithmetic Library) for efficient manipulation.
  3. Not considering the order of operations: Remember that multiplication and division have higher precedence than addition and subtraction, so you should group digits appropriately when building the reversed number.
  4. Using bitwise operations inappropriately: While it is possible to reverse a binary representation of a number using bitwise operations, this method may not be as straightforward or intuitive for decimal numbers.
  5. Not considering edge cases: Ensure that your code handles all valid inputs, including numbers with leading zeros, very large numbers, and negative numbers.

Practice Questions

  1. Write a function that reverses a string in C++.
  2. Implement the iterative method for reversing a number using pointers instead of recursion.
  3. Modify the recursive method to handle negative numbers correctly.
  4. Write a function that returns the reversed digits of a number as an array (without converting it back into a number).
  5. Write a function that reverses a floating-point number by first converting it to an integer, reversing the integer part, and then converting it back into a floating-point number with some loss of precision.
  6. Write a function that checks if a number is a palindrome (i.e., reads the same forwards and backwards).
  7. Write a function that finds all palindromes within a given range of numbers.
  8. Implement an efficient method to reverse a large number using GMP library.
  9. Write a function that reverses a number in hexadecimal representation.
  10. Write a function that reverses a number in binary representation.

FAQ

  1. Why is it important to reverse a number in C++? Reversing a number can be useful for solving various programming problems, such as palindrome detection, data encoding, and debugging issues caused by incorrect input order. Additionally, understanding the concept of reversing a number will provide a foundation for more advanced topics such as big integer arithmetic and number theory.
  2. What are the advantages of using recursion over iteration for reversing a number in C++? Recursion is often more elegant and easier to understand for small-scale problems like reversing a number. However, it can be less efficient than iteration for large numbers due to the overhead of function calls.
  3. Can I use bitwise operations to reverse a number in C++? Yes, you can use bitwise operations to reverse a binary representation of a number. However, this method is not as straightforward or intuitive as the iterative and recursive methods for reversing decimal numbers.
  4. Is it possible to reverse a floating-point number in C++? Floating-point numbers are represented internally using approximations, making it impossible to perform exact reversal operations on them. However, you can convert a floating-point number into an integer, reverse the integer part, and then convert it back into a floating-point number with some loss of precision.
  5. Why is it important to consider edge cases when reversing a number in C++? Edge cases help ensure that your code handles all valid inputs correctly, which is crucial for writing robust and reliable software. By considering edge cases, you can avoid unexpected behavior and improve the overall quality of your code.
Reverse a Number | C++ | XQA Learn