数制转换问题,要求:键盘输入一个十进制数,输出对应的二级制数。如:65à1000001B (要求采用顺序栈或链栈实现,或者分别实现。)
时间: 2023-05-29 19:05:10 浏览: 76
以下是使用顺序栈实现的代码:
```python
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def is_empty(self):
return len(self.items) == 0
def decimal_to_binary(decimal):
stack = Stack()
while decimal > 0:
remainder = decimal % 2
stack.push(remainder)
decimal //= 2
binary = ""
while not stack.is_empty():
binary += str(stack.pop())
return binary + "B"
decimal = int(input("请输入一个十进制数:"))
binary = decimal_to_binary(decimal)
print(f"{decimal}的二进制表示为:{binary}")
```
以下是使用链栈实现的代码:
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.top = None
def push(self, item):
node = Node(item)
node.next = self.top
self.top = node
def pop(self):
if self.is_empty():
raise Exception("栈已空")
item = self.top.data
self.top = self.top.next
return item
def is_empty(self):
return self.top is None
def decimal_to_binary(decimal):
stack = Stack()
while decimal > 0:
remainder = decimal % 2
stack.push(remainder)
decimal //= 2
binary = ""
while not stack.is_empty():
binary += str(stack.pop())
return binary + "B"
decimal = int(input("请输入一个十进制数:"))
binary = decimal_to_binary(decimal)
print(f"{decimal}的二进制表示为:{binary}")
```