C++ reverse number: In the previous article, we have discussed about C++ Program to Calculate Power of a Number. Let us learn how to Reverse a Number in C++ Program.
Methods to Reverse a Number in C++
How to reverse a number c++: In this article, we will see different methods of how we can reverse a number in c++. Let see all the methods one by one.
Method1-Using while loop
get4321.com: In this method, we extract the digit of a number a through this we will make a new number which is the reverse of the given number. Let’s write the code to understand this.
#include <iostream>
using namespace std;
int main() {
int n, reversedNumber = 0, remainder;
n=1234;
while(n != 0) {
remainder = n%10;
reversedNumber = reversedNumber*10 + remainder;
n /= 10;
}
cout << "Reversed Number = " << reversedNumber;
return 0;
}
Output
Reversed Number = 4321
Now lets see how this work. Suppose our number is 1234.
Iteration1- remainder-4 reversedNumber=(0*10)+4=4 number=1234/10=123
Iteration2- remainder-3 reversedNumber=(4*10)+3=43 number=123/10=12
iteration3- remainder-2 reversedNumber=(43*10)+2=432 number=12/10=1
iteration4- remainder-1 reversedNumber=(432*10)+1=4321 number=1/10=0
As the number become 0 so we come out of the loop and we get 4321 as our reversed number.
Method 2-By converting number to string
In this method first, we convert our number to a string. For this we use inbuilt method in c++ to_string().Then we reverse the string using the reverse() method in c++. And then we convert that reverse string again to a number using stoi() method. Let write the code for this.
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, reversedNumber = 0, remainder;
n=1234;
string s=to_string(n);
reverse(s.begin(),s.end());
n=stoi(s);
cout << "Reversed Number = " << n;
return 0;
}
Output
Reversed Number = 4321
So these are the methods to reverse a number in c++.