C++ Program to Reverse a Number

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

  1. Take the input from the user
  2. Perform remainder = number % 10
  3. Print remainder
  4. Perform number/10
  5. 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

  1. Create a reverse(int n), a recursive function of void type.
  2. Base condition will be : if (n <10) then print(n) and return.
  3. 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 questions on our MYCODE platform. These questions are created by our experts so we hope this article will build your logic-building skills and enhance your programming skills.

Leave a Reply

Your email address will not be published. Required fields are marked *