Reverse a Number in C++
Last Updated :
21 Sep, 2023
Improve
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.

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++ 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;
}
27
1
// C++ program to implement
2
// the above approach
3
4
using namespace std;
5
6
// Iterative function to
7
// reverse digits of num
8
int reverseDigits(int num)
9
{
10
int rev_num = 0;
11
while (num > 0) {
12
rev_num = rev_num * 10 + num % 10;
13
num = num / 10;
14
}
15
return rev_num;
16
}
17
18
// Driver code
19
int main()
20
{
21
int num = 4562;
22
cout << "Reverse of num is " << reverseDigits(num);
23
24
getchar();
25
26
return 0;
27
}
Try it on GfG Practice
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.
