设计算法,把十进制整数转换为二至九进制之 间的任一进制输出。请使用顺序栈和链栈两种 数据结构分别设计并给出代码
时间: 2024-10-21 16:03:00 浏览: 40
设计算法把十进制整数转换为二至九进制之间的任一进制输出.txt
将十进制整数转换成其他任意进制,可以采用“除余”(也称为“取模”)法。这里我会分别提供顺序栈和链栈的数据结构实现算法。
### 使用顺序栈
```python
def decimal_to_base_with_stack(decimal_num, base):
if not isinstance(decimal_num, int) or not isinstance(base, int) or decimal_num < 0 or base < 2 or base > 9:
return "输入错误"
stack = list()
digits = '0123456789ABCDEF' if base == 16 else '0123456789'
while decimal_num > 0:
remainder = decimal_num % base
stack.append(digits[remainder])
decimal_num //= base
# 从栈顶到栈底反转得到结果
result = ''.join(stack[::-1])
return result
# 示例
decimal_num = 123
base = 7
print(f"{decimal_num}转为{base}进制为:", decimal_to_base_with_stack(decimal_num, base))
```
### 使用链栈(假设已有一个Node类表示链栈节点)
```python
class Node:
def __init__(self, value=None):
self.value = value
self.next = None
def decimal_to_base_with_linked_stack(decimal_num, base):
if not isinstance(decimal_num, int) or not isinstance(base, int) or decimal_num < 0 or base < 2 or base > 9:
return "输入错误"
class BaseStack(Node):
pass
top = BaseStack()
top.value = decimal_num % base
decimal_num //= base
current = top
while decimal_num > 0:
next_node = BaseStack(current.value)
current.next = next_node
current = next_node
decimal_num //= base
current.value = decimal_num % base
decimal_num //= base
# 遍历链栈获取结果
result = ""
node = top
while node is not None:
result += str(node.value)
node = node.next
return result
# 示例
decimal_num = 123
base = 7
print(f"{decimal_num}转为{base}进制为:", decimal_to_base_with_linked_stack(decimal_num, base))
```
这两种方法都会首先计算出每一位的值,并存储在栈里。顺序栈是线性的,而链栈则更节省空间,特别是当数字较大,位数较多时。
阅读全文