Summary: In this example, we will learn different ways to reverse a number in the C++ programming language.


Method 1: Using While Loop

The idea is to extract the digits from the input number in reverse order and append them to form its reverse using the while loop.


Enter a Number: 243
Reverse: 342

To extract and append the digits from the original number to its reverse we use the following: rev =rev*10 + num%10.

After the operation on each digit, we remove it from the input number using the following: num=num/10.

Method 2: Using Recursion

What we have implemented in the above method can also be implemented using recursion.

To append the digits in reverse order in the recursive approach:

  1. Extract the last digit i.e. num%10
  2. Multiply the digit with pow(10, l-1), where l is the length of the number passed as an argument
  3. Add the result to the next recursive call.


Enter a Number: 859
Reverse: 958

For each recursive call, we are eliminating the last digit from the number using num/10 and also decreasing the length of the number by 1 i.e. l-1.

Method 3: Converting int To string

We can transform the integer into a string using the inbuilt to_string() method and reverse it by using any string reversal methods in C++.


Enter a Number: 700
Reverse: 007

These were the three methods using which we can reverse any number in C++ programming language.

Leave a Reply

one × 5 =