Sunday, August 8, 2021

Convert Decimal Integer to Binary using Stack

 Challenge yourself to solve the problem in this lesson!

We'll cover the following

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.

0 1 1 1 1 1 0 0 MSB (Most Significant Bit) LSB (Least Significant Bit) Therefore the binary equivalent for 242 is: 11110010 242 / 2 = 121 121 / 2 = 60 60 / 2 = 30 30 / 2 = 15 15 / 2 = 7 7 / 2 = 3 3 / 2 = 1 1 / 2 = 0
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!


solution:


class Stack():
    def __init__(self):
        self.items = []

    def push(self, item):
        self.items.append(item)				

    def pop(self):
        return self.items.pop()
    
    def is_empty(self):
        return self.items == []
    
    def peek(self):
        if not self.is_empty():
            return self.items[-1]
        
    def get_stack(self):
        return self.items

def convert_int_to_bin(dec_num):
  stack= Stack()
  quotient=int(dec_num)
  while quotient>0:
    stack.push(quotient%2)
    quotient=quotient//2

  bin_number = ""
  while not stack.is_empty():
    bin_number+=str(stack.pop())

  return bin_number

print(convert_int_to_bin(345))

more formatted on:

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)
main.py
stack.py
0.79s
4 of 4 Tests Passed
ResultInputExpected OutputActual OutputReason
convert_int_to_bin(99)11000111100011Succeeded
convert_int_to_bin(3)1111Succeeded
convert_int_to_bin(71)10001111000111Succeeded
convert_int_to_bin(40)101000101000Succeeded

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 0 is 0.

On line 6, we declare a stack and proceed to a while loop on line 8 which executes if dec_num is greater than 0.

As stated in the division by 2 method, we calculate the remainder of the division of dec_num by 2 and push it onto the stack (lines 9-10). Then we divide dec_num by 2 using the // operator to dec_num which floors the answer of the division, and we update dec_num with the answer (line 11). We keep executing the code on lines 9-11 as long as dec_num is greater than 0. As soon as dec_num becomes equal to or less than 0, the while loop terminates.

On line 13bin_num is declared as an empty string. The while loop on the very next line executes if the stack s is not empty. If s is not empty, we pop a value from s and append it to the bin_num string on line 15. We keep popping elements from s until it becomes empty and the while loop is terminated.

The bin_num is returned from the function on line 17.

The following code helps us to evaluate whether our implementation is correct or not:

  print(int(convert_int_to_bin(56),2)==56)

The above statement will print True if convert_int_to_bin(56) returns the correct binary equivalent for 56. We convert the returned value from convert_int_to_bin(56) to an integer value by specifying base 2 of the returned value. It will convert to 56 if it’s equal to 56 in binary format. Otherwise, the statement will print False if we get some number other than 56.

In this problem, the First-In, Last-Out property of the stack has enabled us to store the binary bits from the MSB (Most Significant Bit) to the LSB (Least Significant Bit), although we get the values in reverse order by the division by 2 method.

Below are some slides that will help you understand the code even better:

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_numdec_num = 0remainder = 1bin_num = "1010" top
30 of 30

Hope everything’s clear up until now! We’ll now move on to the next chapter which is all about Singly Linked Lists.

No comments:

Post a Comment