编写代码利用顺序栈将二进制转八进制,十进制,十六进制
时间: 2023-08-17 10:05:05 浏览: 78
顺序栈、链栈将10进制转为2、8、16进制源码
5星 · 资源好评率100%
以下是使用顺序栈实现二进制转八进制、十进制、十六进制的代码:
```python
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return len(self.items) == 0
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1]
def size(self):
return len(self.items)
def binary_to_decimal(binary):
decimal = 0
index = 0
for i in range(len(binary)-1, -1, -1):
decimal += int(binary[i]) * 2**index
index += 1
return decimal
def decimal_to_octal(decimal):
octal = Stack()
while decimal > 0:
remainder = decimal % 8
octal.push(str(remainder))
decimal //= 8
result = ''
while not octal.is_empty():
result += octal.pop()
return result
def decimal_to_hexadecimal(decimal):
hexadecimal = Stack()
while decimal > 0:
remainder = decimal % 16
if remainder < 10:
hexadecimal.push(str(remainder))
else:
hexadecimal.push(chr(ord('A') + remainder - 10))
decimal //= 16
result = ''
while not hexadecimal.is_empty():
result += hexadecimal.pop()
return result
if __name__ == '__main__':
binary = input('请输入二进制数:')
decimal = binary_to_decimal(binary)
print(f'转换为十进制:{decimal}')
octal = decimal_to_octal(decimal)
print(f'转换为八进制:{octal}')
hexadecimal = decimal_to_hexadecimal(decimal)
print(f'转换为十六进制:{hexadecimal}')
```
运行结果:
```
请输入二进制数:1011101
转换为十进制:93
转换为八进制:135
转换为十六进制:5D
```
阅读全文