Open In App

JavaScript Program to Convert Decimal to Binary Using Recursion

Last Updated : 26 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

JavaScript allows us to convert decimal numbers to their binary equivalents using recursion, offering two distinct approaches. Through recursive division and concatenation, the first method constructs the binary representation directly.

The second method leverages a string and recursion, providing an alternative approach. Each method’s time and space complexities are also discussed, providing insights into their efficiency and suitability for various scenarios.

Using Recursion

In this method, we recursively divide the decimal number by 2 and append the remainder to construct the binary representation.

Syntax:

findBinary(decimal)
if (decimal == 0)
binary = 0
else
binary = decimal % 2 + 10 * (findBinary(decimal / 2))

Example: The below code converts Decimal to Binary Using Recursion

JavaScript
function findBinary(decimal) {
    if (decimal == 0) {
        return 0;
    } else {
        return ((decimal % 2) + 10 * findBinary(parseInt(decimal / 2)));
    }
}

// Driver code
let decimal_number = 10;
console.log(findBinary(decimal_number));

Output
1010

Time Complexity: O(log2n), Here n is the decimal_number.
Auxiliary Space: O(1), As constant extra space is used.

Using Recursion and vector of bool

In this approach we recursively divide the decimal number by 2 and instead of directly appending the remainder to construct the binary representation we append the remainder to a string representing the binary digits.

Example: The below code converts Decimal to Binary Using Recursion and vector of bool

JavaScript
let bin_num = "";

function deci_to_bin(x) {
    if (x <= 1) {
        bin_num += String.fromCharCode(x + '0'.charCodeAt());
    } else {
        deci_to_bin(parseInt(x / 2, 10));

        // If x is divisible by 2
        if (x % 2 != 0)
            bin_num += '1';
        // otherwise
        else
            bin_num += '0';
    }
}

deci_to_bin(231576);

console.log(bin_num);

Output
111000100010011000

Time Complexity: O(log n), where n is given decimal number
Auxiliary Space: O(log n)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads