...
/Solution Review: Convert Decimal Number to Binary Number
Solution Review: Convert Decimal Number to Binary Number
We'll cover the following...
Solution: Using Recursion
Press + to interact
def decimalToBinary(testVariable) :# Base Caseif testVariable <= 1:return str(testVariable)# Recursive Caseelse:return decimalToBinary(testVariable // 2) + decimalToBinary(testVariable % 2) # Floor division -# division that results into whole number adjusted to the left in the number line# Driver CodetestVariable = 11print(decimalToBinary(testVariable))
Explanation:
The simple method for converting a decimal number to a binary number is to keep track of the and the leftover when a number is divided by . Look at the illustration below:
Converting Decimal Number to Binary Number
We continue dividing the number by until we are left with .
Since divided by gives ; 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 and the 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.
to save progress
Challenge 3: Convert Decimal Number to Binary Number
Test Your Knowledge 3
to save progress