利用顺序栈实现十进制转二进制。代码
时间: 2023-06-06 11:04:23 浏览: 98
好的,以下是利用顺序栈实现十进制转二进制的代码,供你参考:
```python
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return len(self.items) == 0
def push(self, item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
def peek(self):
if not self.is_empty():
return self.items[-1]
def size(self):
return len(self.items)
def decimal_to_binary(decimal_num):
stack = Stack()
while decimal_num > 0:
remainder = decimal_num % 2
stack.push(remainder)
decimal_num //= 2
binary_num = ""
while not stack.is_empty():
binary_num += str(stack.pop())
return binary_num
# 测试代码
print(decimal_to_binary(10)) # 输出 1010
print(decimal_to_binary(23)) # 输出 10111
```
阅读全文