Given a number num, write a C++ Program to reverse the given number using Recursion.
Example: Input: num = 1234 Output: 4321 Input: num = -345 Output: -543
To solve this problem, you must have some prior knowledge of C++ programming and Recursion.
Follow the steps given below to reverse a number using Recursion.
- In the reverse function, we first check if the number is zero. If it is, we return from the function, as there's nothing to reverse.
- If the number is not zero, we output the last digit of the number using the modulo operator (%).
- We then call the reverse function again, passing the number divided by 10, to remove the last digit.
- This process continues until the number becomes zero.
C++ code to Reverse a Positive Number.
//C++ Program to reverse positive number using Recursion #include <iostream> using namespace std; //function call void reverse(int num) { if (num == 0) { return; } cout << num % 10; reverse(num / 10); } int main() { int num; cout << "Enter a number: "; cin >> num; cout << "The reverse of the number is: "; reverse(num); cout << endl; return 0; }
Enter a number: 4738
The reverse of the number is: 8374- Time Complexity: O(log(n))
- Auxiliary Space: O(log(n))
Note: The above algorithm can reverse only positive numbers so to reverse both positive and negative numbers, we have made some changes in the above algorithm. (alert-passed)
Reverse a Negative Number in C++
Following steps to reverse both positive and negative numbers using recursion:
- If the number is not zero, we output the last digit of the number using the abs function and modulo operator (%).
- We then call the reverse function again, passing the absolute value of the number divided by 10, to remove the last digit.
- This process continues until the number becomes zero.
- We read the input number and check if it's negative. If it is, we output a negative sign before calling the reverse function.
C++ code to reverse both positive and negative numbers.
//C++ Program to reverse both positive and negative num #include <iostream> using namespace std; //function call void reverse(int num) { if (num == 0) { return; } cout << abs(num % 10); reverse(num / 10); } int main() { int num; cout << "Enter a number: "; cin >> num; cout << "The reverse of the number is: "; //checking if num is negative if (num < 0) { cout << "-"; } reverse(abs(num)); cout << endl; return 0; }
Output:
Enter a number: -14738
The reverse of the number is: -83741- Time Complexity: O(log(n))
- Auxiliary Space: O(log(n))
No comments:
Post a Comment