用栈链的方式将十进制数转换为二进制和八进制
时间: 2024-05-03 14:21:52 浏览: 78
利用栈将十进制转换成二进制
3星 · 编辑精心推荐
这里提供一个利用栈链将十进制数转换为二进制和八进制的示例代码:
```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 size(self):
return len(self.items)
def decimal_to_binary(decimal):
binary_stack = Stack()
while decimal > 0:
binary_stack.push(decimal % 2)
decimal //= 2
binary_str = ''
while not binary_stack.is_empty():
binary_str += str(binary_stack.pop())
return binary_str
def decimal_to_octal(decimal):
octal_stack = Stack()
while decimal > 0:
octal_stack.push(decimal % 8)
decimal //= 8
octal_str = ''
while not octal_stack.is_empty():
octal_str += str(octal_stack.pop())
return octal_str
decimal_num = 12345
binary_num = decimal_to_binary(decimal_num)
octal_num = decimal_to_octal(decimal_num)
print(f'The binary representation of {decimal_num} is {binary_num}')
print(f'The octal representation of {decimal_num} is {octal_num}')
```
运行结果:
```
The binary representation of 12345 is 11000000111001
The octal representation of 12345 is 30071
```
该示例代码定义了一个栈类,包含了栈的基本操作方法。在将十进制数转换为二进制和八进制的函数中,首先创建了一个空栈,然后通过不断取余和整除的方式将十进制数转换为对应进制下的数,并将每个位上的数字压入栈中。最后,通过弹出栈中的数字得到转换后的字符串表示。
阅读全文