C++ Program to find the Reverse of a Number

Program Reverse a Number in C++

Here we will discuss how to find the reverse of a given number using C++ programming language.
We will use loop and arithmetic operators

1. Modulo Operator : '%'
2. Division Operator : '/'

Example:
Number: 5678
Reverse: 8765
reverse

Method 1

Algorithm:-

For a user input num

  • Initialize reverse = 0, rem
  • Extract the last digit of num (rem = num % 10)
  • Multiply reverse with 10 & add remainder (reverse = reverse * 10 + rem)
  • Reduce the original number (num = num/10)
  • Keep doing this until original number becomes 0
reverse a number in c++

C++ Code

Run
#include <iostream>
using namespace std;

//main program
int main ()
{
    //variables initialization
    int num, reverse = 0, rem;
    num=1234;
    cout <<"\nThe number is"<<num; 
  
    //loop to find reverse number
    while(num != 0)
    {
      rem = num % 10;
      reverse = reverse * 10 + rem;
      num /= 10;
    };
 
    //output
    cout <<"\nReversed Number: "<<reverse;
    
    return 0;
}
// Time complexity : O(N)
// Space complexity : O(1)
// where N is number of digits in num

Output

The number is: 1234
Reversed Number: 4321

Method 2

This method uses recursion in c++. Please go through this page if you are new to recursion

C++ Code

Run
#include <iostream>
using namespace std;

int getReverse(int num, int rev){
    if(num == 0)
        return rev;
    
    int rem = num % 10;
    rev = rev * 10 + rem;
    
    return getReverse(num / 10, rev);
}

//main program
int main ()
{
    int num, rev = 0;
    num=1234;
    cout << "\n The number is"<<num; 
       
    cout << "\nReverse: " << getReverse(num, rev);
}
// Time complexity : O(N)
// Space complexity : O(1)
// Auxilliary Space complexity : O(N) due to function call stack
// where N is number of digits in num

Output

The number is: 1234
Reversed Number: 4321

Method 3

This method uses recursion in c++. Please go through this page if you are new to recursion

This method doesn’t use extra rev variable passed in the recursive function.

C++ Code

Run
#include <iostream>
using namespace std;

void getReverse(int num){
    if(num == 0)
        return;
    
    int rem = num % 10;
    cout << rem;
    
    getReverse(num / 10);
}

//main program
int main ()
{
    int num, rev = 0;
    num=1234;
    cout << "\nThe number is: "<<num; 
    
    
    cout << "\nReverse: ";
    getReverse(num);
}
// Time complexity : O(N)
// Space complexity : O(1)
// Auxilliary Space complexity : O(N) due to function call stack
// where N is number of digits in num

Output

The number is: 1234
Reversed Number: 4321

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 150+ courses offered by PrepInsta in One Subscription