Decimal to Binary
  • Convert a decimal number to its binary number
    1. # StackModule.py
    2. #!/usr/bin/python3
    3. import copy
    4.  
    5. class Stack(object):
    6. def __init__(self):
    7. self.items = []
    8.  
    9. def isEmpty(self):
    10. return len(self.items) == 0
    11.  
    12. def push(self, element):
    13. try:
    14. self.items.append(element)
    15. return True
    16. except Exception as e:
    17. return False
    18.  
    19. def pop(self):
    20. try:
    21. return self.items.pop()
    22. except Exception as e:
    23. return None
    24.  
    25. def peek(self):
    26. try:
    27. return self.items[len(self.items)-1]
    28. except Exception as e:
    29. return None
    30.  
    31. def size(self):
    32. return len(self.items)
    33.  
    34. def __str__(self):
    35. output = []
    36.  
    37. items = copy.copy(self.items)
    38. items.reverse()
    39.  
    40. for item in items:
    41. output.append(str(item))
    42.  
    43. return " -> ".join(output)
    1. #!/usr/bin/python3
    2. from StackModule import Stack
    3.  
    4. def decimal2binary(d):
    5. s = Stack()
    6.  
    7. while d > 0:
    8. rem = d%2
    9. d = d//2
    10. s.push(rem)
    11.  
    12. b = ''
    13. while s.size() > 0:
    14. b = b+str(s.pop())
    15.  
    16. return b
    17.  
    18. if __name__ == '__main__':
    19. print(decimal2binary(9)) # 1001
    20. print(decimal2binary(233)) # 11101001
    Reference
  • Problem Solving with Algorithms and Data Structures using Python