Search⌘ K

Solution Review: Convert Decimal Integer to Binary

Understand how to convert decimal integers to binary using a stack in Python. Explore handling edge cases and implementing the division by 2 method, leveraging the LIFO property of stacks to reverse binary bits accurately.

We'll cover the following...

Let’s analyze the solution to the exercise in the previous lesson.

Implementation

Python 3.5
def convert_int_to_bin(dec_num):
if dec_num == 0:
return 0
s = Stack()
while dec_num > 0:
remainder = dec_num % 2
s.push(remainder)
dec_num = dec_num // 2
bin_num = ""
while not s.is_empty():
bin_num += str(s.pop())
return bin_num
print(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 00 ...