Search⌘ K

Solution Review: Convert Decimal Number to Binary Number

Explore how to implement a recursive function that converts decimal numbers to binary. Understand base and recursive cases, track remainders and dividends, and follow the function call sequence to grasp the step-by-step recursion process in Python.

We'll cover the following...

Solution: Using Recursion

Python 3.5
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:

To convert a decimal number to a binary number, keep track of the remainderremainder and the remaining dividenddividend ...