Decimal to Binary
  • Convert a decimal number to its binary number
  • # StackModule.py
    #!/usr/bin/python3
    import copy
    
    class Stack(object):
        def __init__(self):
            self.items = []
    
        def isEmpty(self):
            return len(self.items) == 0
    
        def push(self, element):
            try:
                self.items.append(element)
                return True
            except Exception as e:
                return False
    
        def pop(self):
            try:
                return self.items.pop()
            except Exception as e:
                return None
    
        def peek(self):
            try:
                return self.items[len(self.items)-1]
            except Exception as e:
                return None
    
        def size(self):
            return len(self.items)
    
        def __str__(self):
            output = []
    
            items = copy.copy(self.items)
            items.reverse()
    
            for item in items:
                output.append(str(item))
    
            return " -> ".join(output)
                
    #!/usr/bin/python3
    from StackModule import Stack
    
    def decimal2binary(d):
        s = Stack()
    
        while d > 0:
            rem = d%2
            d = d//2
            s.push(rem)
    
        b = ''
        while s.size() > 0:
            b = b+str(s.pop())
    
        return b
    
    if __name__ == '__main__':
        print(decimal2binary(9)) # 1001
        print(decimal2binary(233)) # 11101001
                
    Reference
  • Problem Solving with Algorithms and Data Structures using Python