Problem Statement:
Given a decimal number, convert into binary number using recursion
Example:
Input:
n = 7
Output: 111
Solution Explanation:
In this approach, we recursively divide the decimal number by 2 and append the remainder as the next binary digit.
Constructing the binary representation from right to left
Time Complexity: O(log2n)
Space Complexity: O(log2n)
Code Solution
#include <iostream>
#include <cmath>
using namespace std;
int solution(int num)
{
//base case
if (num == 0)
return 0;
else
return (num % 2 + 10 * solution(num / 2));
}
int main()
{
int num = 7;
cout << solution(num);
return 0;
}
Output
111