I do not understand the concept of how I can pop an integer from a stack and convert it into binary.
I successfully created a program that can take in an integer and convert it to binary by pushing it into an array using stack but I am not sure how I can make my input a stack itself where I can pop each integer in a stack and then push them into an array to change it into binary.
class ArrayStack: #puts in and removes from the top only
def __init__(self):
self._data = [ ]
def __len__(self):
return len(self._data)
def is_empty(self):
return len(self._data) == 0
def push(self, e):
self._data.append(e)
def top(self):
if self.is_empty( ):
raise Exception("No Elements in Stack")
return self._data[-1]
def pop(self):
if self.is_empty( ):
raise Exception("No Elements in Stack")
return self._data.pop()
def decToBin(num):
stack = ArrayStack()
while num > 0:
remainder = num % 2
stack.push(remainder)
num = num // 2
_str = ''
while not stack.is_empty():
Bin = stack.pop()
_str = _str + str(Bin)
return int(_str)
if __name__ == "__main__":
print(decToBin(65536))
New contributor
Satvik Konda is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.