In this article, we will see how to reverse a number. We can reverse a number using loops and arithmetic operators in iterative and recursive approaches. If you are a beginner in the programming world then this article will be for you. We will solve this problem in different ways.
Example:
Input: 12345
Output: 54321
Algorithm to Reverse a Number
- Take the input from the user
- Perform remainder = number % 10
- Print remainder
- Perform number/10
- Repeat steps 2 and 4 until the input number cannot be further divided.
Method 1: An iterative method to reverse a number
In this method, we will use a while loop to reverse a number.
Code Implementation to reverse a number using iterative method
#include <iostream> using namespace std; int main() { int number, rev = 0, remainder; cout << "\nEnter a number : "; cin >> number; cout << "\nReversed Number : "; while(number != 0) { remainder = number%10; rev = rev*10 + remainder; number /= 10; } cout << rev << endl; return 0; }
Output:
Enter a number: 12345
Reversed number: 54321
Time Complexity: O(log(N))
Method 2: Recursive program to reverse a number
In this method, we will use a recursive function to apply the reverse a number in which the function call itself from its definition part.
Algorithm to reverse a number recursively
- Create a reverse(int n), a recursive function of void type.
- Base condition will be : if (n < 10) then print(n) and return.
- Otherwise, print(n%10) and call function reverse(n/10).
Code Implementation to reverse a number recursively
#include <bits/stdc++.h> using namespace std; int reverse_digits(int num) { static int rev_num = 0; static int base_pos = 1; if(num > 0) { reverse_digits(num/10); rev_num += (num%10)*base_pos; base_pos *= 10; } return rev_num; } int main() { int num; cout << "\nEnter a number: "; cin >> num; cout << "\nReversed number : " << reverse_digits(num); return 0; }
Output:
Enter a number: 12345
Reversed number: 54321
Conclusion
This blog taught you the most efficient and effective way how to reverse a number in C++. we have discussed two methods with their respective algorithms and time complexities. We hope this blog will help you to clear your fundamentals. Many companies like TCS, Wipro, Tech Mahindra, and Accenture ask these types of questions for checking the candidate’s fundamental and logical knowledge. Also, you can practice more C++ Programs. and questions on our platform. These questions are created by our experts so we hope this article will build your logic-building skills and enhance your programming skills.
Other C++ Programs
C++ Program to Add Two Numbers
C++ program for heap sort
Bubble Sort in C++ with Program Code and Example