编程用栈实现十进制与八进制之间的相互转换
时间: 2024-02-27 20:53:19 浏览: 135
以下是使用栈实现十进制与八进制相互转换的代码:
```python
class Stack:
def __init__(self):
self.stack = []
def is_empty(self):
return self.stack == []
def push(self, item):
self.stack.append(item)
def pop(self):
return self.stack.pop()
def peek(self):
return self.stack[-1]
def size(self):
return len(self.stack)
def decimal_to_octal(decimal_num):
# 将十进制数转换为八进制数
stack = Stack()
while decimal_num > 0:
remainder = decimal_num % 8
stack.push(remainder)
decimal_num //= 8
octal_num = ""
while not stack.is_empty():
octal_num += str(stack.pop())
return octal_num
def octal_to_decimal(octal_num):
# 将八进制数转换为十进制数
decimal_num = 0
power = 0
while octal_num != "":
digit = int(octal_num[-1])
decimal_num += digit * (8 ** power)
power += 1
octal_num = octal_num[:-1]
return decimal_num
```
使用示例:
```python
if __name__ == '__main__':
decimal_num = 123
octal_num = decimal_to_octal(decimal_num)
print("Decimal %d is converted to octal %s" % (decimal_num, octal_num))
octal_num = "173"
decimal_num = octal_to_decimal(octal_num)
print("Octal %s is converted to decimal %d" % (octal_num, decimal_num))
```
输出结果:
```
Decimal 123 is converted to octal 173
Octal 173 is converted to decimal 123
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![py](https://img-home.csdnimg.cn/images/20250102104920.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)