Open In App

Reverse a Number in C++

Last Updated : 21 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn to write a C++ program to reverse a number. Reversing the digits of a number means changing the order of the digits of the number so that the last digit becomes the first digit, the second last digit becomes the second digit, and so on. The number upon reversing read the same as reading the original number backward.

For example, if the number num is 12548, the reverse of the number num is 84521.

reverse a number in C++

 

Algorithm to Reverse Digits of a Number

Let us assume the number to be reversed is num and the reversed number will be stored in rev_num.

  • Initialize rev_num = 0.
  • Run a loop till num > 0.
  • The rightmost digit of num can be obtained by performing modulo by 10 (num % 10).
  • Now, the rightmost digit obtained is added to the reversed number by shifting its digits one position to the left.
    • rev_num = rev_num*10 + num%10;
  • Remove the last digit from num by dividing it by 10 (num = num / 10).
  • After the loop, return rev_num which holds the reverse of digits of the number num.

C++ Program to Reverse a Number

C++




// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Iterative function to
// reverse digits of num
int reverseDigits(int num)
{
    int rev_num = 0;
    while (num > 0) {
        rev_num = rev_num * 10 + num % 10;
        num = num / 10;
    }
    return rev_num;
}
  
// Driver code
int main()
{
    int num = 4562;
    cout << "Reverse of num is " << reverseDigits(num);
  
    getchar();
  
    return 0;
}


Output

Reverse of num is 2654

Complexity Analysis

Time Complexity: O(log(n)), where n is the input number. 
Auxiliary Space: O(1)

Flow of Program To Reverse a Number

The below image illustrates the flow of the program to reverse the digits of a number.

Flowchart for reversing a number

Related Articles


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads