Search⌘ K
AI Features

Solution Review: Convert Decimal Number to Binary Number

Explore how to apply recursion to convert decimal numbers into binary. Understand the base case and recursive steps that track dividends and remainders, enabling you to solve binary conversion problems confidently.

We'll cover the following...

Solution: Using Recursion

Javascript (babel-node)
function decimalToBinary(testVariable) {
// Base case
if (testVariable <= 1) {
return String(testVariable)
}
// Recursive case
else {
return decimalToBinary(Math.floor(testVariable / 2)) + decimalToBinary(testVariable % 2)
}
}
// Driver Code
var testVariable = 11
console.log(decimalToBinary(testVariable))

Explanation:

The simple method for converting a decimal number to a binary number is to keep track of the remainderremainder and the leftover dividenddividend ...