Problem Statement:
You are given a decimal number, you need to convert into binary number using recursion.
Example:
Input: 15
Output: 1111
Solution Explanation:
To get the binary number you need to use modulus operator “N%2”.
Then recursively call the function with the value (N/2).
The base case will be when “N==0”, we return from the function.
Time Complexity: O(logN)
Space Complexity: O(logN)
Code Solution
#include <iostream>
using namespace std;
void solution(int n)
{
// base case
if (n == 0) {
cout << "0";
return;
}
solution(n / 2);
cout << n % 2;
}
int main()
{
int n = 5;
solution(n);
return 0;
}
Output
0101