为什么我的 python 使用堆栈将数字转换为二进制的代码不起作用?

Why is my python code to convert an number to binary using stack not working?

以下是我使用Python3编写的堆栈将数字转换为二进制的代码。 每当我 运行 它时,都会生成 None 作为输出。这可能是什么原因造成的?提前致谢。

class Stack():
    def __init__(self):
        self.stack = []
        self.top = -1

def push(self, val):
    self.stack.append(val)
    self.top += 1

def pop(self):
    if self.top == -1:
        print('Underflow')
    else:
        del self.stack[self.top]
        self.top -= 1

def empty(self):
    return self.stack == []

def peek(self):
    return self.top

def display(self):
    return self.stack

def binary(n):
    b = Stack()
    while n > 0:
        r = n%2
        b.push(r)
        n = n//2

    bn = ''
    while not b.empty():
        bn += str(b.pop())

    return bn

print(binary(242))

这一行只是弹出栈中的元素,并没有return anything.It returns None.

bn += str(b.pop()) 

您必须将顶部元素存储在一个变量中,然后在它之后弹出堆栈。

在你的二元函数中试试下面这个:

def binary(n):
    b = Stack()
    while n > 0:
        r = n % 2
        b.push(r)
        n = n//2
    print(b.stack)
    bn = ''
    while not b.empty():
        bn += str(b.stack[-1])
        b.pop()
    return bn