Exercise: Convert Decimal Integer to Binary
Challenge yourself to solve the problem in this lesson!
WE'LL COVER THE FOLLOWING
• Division by 2 Method
• Coding Time!
In this coding exercise, you are required to use the stack data structure to
convert integer values to their binary equivalent.
Division by 2 Method #
The slides below show how to use the division by 2 method to compute the
binary equivalent for an integer.
242 / 2 = 121 0
Integer Value from the division Remainder
Divide the number by two.
Extract the non-fractional part from the answer
and record the remainder from the division.
1 of 10
242 / 2 = 121 0
121 / 2 = 60 1
Keep dividing the answer from the previous
calculation by two until you reach zero
and keep recording the remainders.
2 of 10
242 / 2 = 121 0
121 / 2 = 60 1
60 / 2 = 30 0
3 of 10
242 / 2 = 121 0
121 / 2 = 60 1
60 / 2 = 30 0
30 / 2 = 15 0
4 of 10
242 / 2 = 121 0
121 / 2 = 60 1
60 / 2 = 30 0
30 / 2 = 15 0
15 / 2 = 7 1
5 of 10
242 / 2 = 121 0
121 / 2 = 60 1
60 / 2 = 30 0
30 / 2 = 15 0
15 / 2 = 7 1
7 / 2 = 3 1
6 of 10
242 / 2 = 121 0
121 / 2 = 60 1
60 / 2 = 30 0
30 / 2 = 15 0
15 / 2 = 7 1
7 / 2 = 3 1
3 / 2 = 1 1
7 of 10
242 / 2 = 121 0
121 / 2 = 60 1
60 / 2 = 30 0
30 / 2 = 15 0
15 / 2 = 7 1
7 / 2 = 3 1
3 / 2 = 1 1
1 / 2 = 0 1
8 of 10
LSB (Least Significant Bit)
242 / 2 = 121 0
121 / 2 = 60 1
60 / 2 = 30 0
30 / 2 = 15 0
15 / 2 = 7 1
7 / 2 = 3 1
3 / 2 = 1 1
1 / 2 = 0 1
MSB (Most Significant Bit)
You have to read from the bottom of the remainders(MSB) to
the top(LSB) to get the binary equivalent of the integer.
9 of 10
LSB (Least Significant Bit)
242 / 2 = 121 0
121 / 2 = 60 1
60 / 2 = 30 0
30 / 2 = 15 0
15 / 2 = 7 1
7 / 2 = 3 1
3 / 2 = 1 1
1 / 2 = 0 1
MSB (Most Significant Bit)
Therefore the binary equivalent for 242 is:
11110010
10 of 10
Coding Time! #
You can build your solution based on division by 2 method. Your solution
should return the correct binary equivalent of dec_num as a string from the
convert_int_to_bin(dec_num) in order to pass the tests.
Make sure that you use stack while solving this challenge. The stack.py has
been imported to the code. You can make use of the implementation while
coding your solution. Remove the pass statement if you start implementing
your solution.
Good luck!
Show Hint
main.py from stack import Stack
def convert_int_to_bin(dec_num):
stack.py pass