Convert a number to binary

Given a decimal base 10 digit such as 120, convert it into binary.

Division by 2 approach

120 / 2 -> 60 remainder 0
60 / 2 -> 30 remainder 0
30 / 2 -> 15 remainder 0
15 / 2 -> 7 remainder 1
7 / 2 -> 3 remainder 1
3 / 2 -> 1 remainder 1

Should return:

00000111

Solution: We use the stack class we created in our earlier example. However a Python list should be able to do the same thing.

  1. Iterate through the string of digits.
  2. Perform modulo division.
  3. Store the remainder of the division into a stack.
from stack import Stack


def convert_int_to_bin(dec_num):
    if dec_num == 0:
        return 0

    s = Stack()

    while dec_num > 0:
        binary = dec_num % 2
        s.push(binary)
        dec_num = dec_num // 2
        print(dec_num)


if __name__ == "__main__":
    print(convert_int_to_bin(12))
from stack import Stack


def convert_int_to_bin(dec_num):
    if dec_num == 0:
        return 0

    s = Stack()

    while dec_num > 0:
        binary = dec_num % 2
        s.push(binary)
        dec_num = dec_num // 2

    bin_num = ""
    while not s.is_empty():
        bin_num += str(s.pop())

    return bin_num

if __name__ == "__main__":
    print(convert_int_to_bin(12))
    print(convert_int_to_bin(1))