Summary: In this example, we will learn different ways to reverse a number in the C++ programming language.
Example:
Input: 456 Output: 654 Input: 132 Output: 231
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.
#include <iostream>
using namespace std;
int main()
{
int num;
//Input a number
cout << "Enter a Number: ";
cin >> num;
//Initialize rev with 0
int rev=0;
//Append digits in reverse order
while(num>0){
rev = rev*10 + num%10;
num = num/10;
}
cout << "Reverse: " << rev;
return 0;
}
Output:
Enter a Number: 243Reverse: 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:
- Extract the last digit i.e.
num%10
- Multiply the digit with
pow(10, l-1)
, wherel
is the length of the number passed as an argument - Add the result to the next recursive call.
#include <iostream>
#include <cmath>
using namespace std;
//recursive_function(number, length_of_the_number)
int reverse(int num, int l){
//base contition
if(num==0)
return 0;
//extract the last digit
int digit = num%10;
/*
*Append them in reverse order
*For e.g., to reverse 859
*return 9*100 + 58 = 958
*/
return digit*pow(10, l-1) + reverse(num/10, l-1);
}
int main()
{
int num;
//Input a number
cout << "Enter a Number: ";
cin >> num;
//call the recursive funtion to reverse the number
int length = to_string(num).length();
int rev = reverse(num, length);
//output the number
cout << "Reverse: " << rev;
return 0;
}
Output:
Enter a Number: 859Reverse: 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++.
#include <iostream>
#include<algorithm>
using namespace std;
int main()
{
int num;
//Input a number
cout << "Enter a Number: ";
cin >> num;
//convert the integer to string
string str = to_string(num);
/*
*reverse the string using the reverse() method
*defined in the algorithm header file
*/
reverse(str.begin(), str.end());
//output the string
cout << "Reverse: " << str;
return 0;
}
Output:
Enter a Number: 700Reverse: 007
These were the three methods using which we can reverse any number in C++ programming language.