Write a program to reverse digits of a number in C++


A program to reverse digits of a number will interchange the position of the digits and reverse there order.

Let’s suppose be a number abcde the reverse will be edcba.

Let’s take an example to understand the problem,

Input

n = 786521

Output

125687

To reverse digits of the number, we will take each digit of the number from MSB(unit digit) and add it to reverse number variable, after this divide the original number by 10 and the reverse_number is multiplied by 10. This will be done until the number becomes 0.

This repetitive process can be accomplished by two methods, iteration, and recursion, we will create a program to create illustrate both the method.

Example

Method 1: Iterative approach

 Live Demo

#include <iostream>
using namespace std;
int reversDigitsIt(int n) {
   int reverseNumber = 0;
   while(n > 0){
      reverseNumber = reverseNumber*10 + n%10;
      n /= 10;
   }
   return reverseNumber;
}
int main() {
   int n = 4562;
   cout<<"The number is : "<<n<<endl;
   cout<<"Reverse of number is "<<reversDigitsIt(n);
   return 0;
}

Output

The number is : 4562
Reverse of number is 2654

Example

 Live Demo

Method 2: Recursive Approach

#include <iostream>
using namespace std;
int reverseNumber = 0;
int numPos = 1;
void reversDigitsRec(int n) {
   if(n > 0){
      reversDigitsRec(n/10);
      reverseNumber += (n%10)*numPos;
      numPos *= 10;
   }
}
int main() {
   int n = 4562;
   cout<<"The number is : "<<n<<endl;
   reversDigitsRec(n);
   cout<<"Reverse of number is "<<reverseNumber;
   return 0;
}

Output

The number is : 4562
Reverse of number is 2654

Updated on: 17-Apr-2020

438 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements