Solution Review: Convert Decimal Integer to Binary
This lesson contains the solution review for the challenge of converting integer values to their binary equivalents.
We'll cover the following...
Let’s analyze the solution to the exercise in the previous lesson.
Implementation
Press + to interact
def convert_int_to_bin(dec_num):if dec_num == 0:return 0s = Stack()while dec_num > 0:remainder = dec_num % 2s.push(remainder)dec_num = dec_num // 2bin_num = ""while not s.is_empty():bin_num += str(s.pop())return bin_numprint(convert_int_to_bin(56))print(convert_int_to_bin(2))print(convert_int_to_bin(32))print(convert_int_to_bin(10))print(int(convert_int_to_bin(56),2)==56)
Explanation
On line 3, we cater to an edge case of dec_num
being equal to 0
. If dec_num
is equal to 0
, we return 0
on line 4 as the binary equivalent for the decimal number ...