编写一个程序,利用栈的特点和基本操作,实现如下功能:将一个100以内的正整数N转换为二进制数,并输出转换后的结果。(注:即可采用顺序栈,也可采用链式栈)
时间: 2024-10-18 16:21:31 浏览: 10
要编写一个程序,首先需要选择一种数据结构来存储数字的每一位,这里我们选择链式栈,因为它更方便插入和删除元素。下面是使用链式栈实现将100以内正整数N转换为二进制的一个Python示例:
```python
class Node:
def __init__(self, data=0):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.top = None
def push(self, data):
new_node = Node(data)
if not self.top:
self.top = new_node
else:
new_node.next = self.top
self.top = new_node
def pop(self):
if not self.is_empty():
popped_data = self.top.data
self.top = self.top.next
return popped_data
else:
return None
def is_empty(self):
return self.top is None
def decimal_to_binary(n, stack):
binary_string = ''
while n > 0:
remainder = n % 2
binary_string = str(remainder) + binary_string
stack.push(remainder)
n //= 2
# Pop the remainders from the stack and append them to the binary string in reverse order
binary_string = ''.join([str(stack.pop()) for _ in range(len(binary_string))])
return binary_string
# Test the function
n = int(input("Enter a number between 0 and 99: "))
stack = Stack()
binary = decimal_to_binary(n, stack)
print(f"Binary representation of {n} is: {binary}")
阅读全文