Solution Review: Convert Decimal Number to Binary Number

We'll cover the following

Solution: Using Recursion

Press + to interact
def decimalToBinary(testVariable) :
# Base Case
if testVariable <= 1:
return str(testVariable)
# Recursive Case
else:
return decimalToBinary(testVariable // 2) + decimalToBinary(testVariable % 2) # Floor division -
# division that results into whole number adjusted to the left in the number line
# Driver Code
testVariable = 11
print(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 when a number is divided by 22. Look at the illustration below:

Converting Decimal Number to Binary Number
Converting Decimal Number to Binary Number

We continue dividing the number by 22 until we are left with 11.

Since 11 divided by 22 gives remainderremainder 11; this will be our base case:

if testVariable <= 1:
    return str(testVariable)

In the recursive case:

return decimalToBinary(testVariable // 2) + decimalToBinary(testVariable % 2)

we keep track of the remaining dividenddividend and the remainderremainder respectively. Have a look at the sequence of function calls to have an idea of how recursion occurs in this case.


In the next lesson, we have a short quiz for you to test your concepts.