Solution Review: Convert Decimal Number to Binary Number
Solution: Using Recursion
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.