通过栈实现进制转换器 实现10进制、2进制、8进制和16进制的相互转换。
时间: 2023-11-26 17:06:26 浏览: 91
好的,这个问题我可以回答。以下是通过栈实现进制转换器的示例代码:
```python
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
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 decimal_to_binary(decimal_num):
stack = Stack()
while decimal_num > 0:
remainder = decimal_num % 2
stack.push(remainder)
decimal_num = decimal_num // 2
binary_string = ""
while not stack.is_empty():
binary_string += str(stack.pop())
return binary_string
def decimal_to_octal(decimal_num):
stack = Stack()
while decimal_num > 0:
remainder = decimal_num % 8
stack.push(remainder)
decimal_num = decimal_num // 8
octal_string = ""
while not stack.is_empty():
octal_string += str(stack.pop())
return octal_string
def decimal_to_hexadecimal(decimal_num):
stack = Stack()
while decimal_num > 0:
remainder = decimal_num % 16
if remainder < 10:
stack.push(remainder)
else:
hexadecimal_digit = chr(ord('A') + remainder - 10)
stack.push(hexadecimal_digit)
decimal_num = decimal_num // 16
hexadecimal_string = ""
while not stack.is_empty():
hexadecimal_string += str(stack.pop())
return hexadecimal_string
def binary_to_decimal(binary_string):
decimal_num = 0
power = 0
for digit in binary_string[::-1]:
decimal_num += int(digit) * 2 ** power
power += 1
return decimal_num
def octal_to_decimal(octal_string):
decimal_num = 0
power = 0
for digit in octal_string[::-1]:
decimal_num += int(digit) * 8 ** power
power += 1
return decimal_num
def hexadecimal_to_decimal(hexadecimal_string):
decimal_num = 0
power = 0
for digit in hexadecimal_string[::-1]:
if digit.isdigit():
decimal_num += int(digit) * 16 ** power
else:
decimal_num += (ord(digit.upper()) - ord('A') + 10) * 16 ** power
power += 1
return decimal_num
```
以上是一个基本的栈实现进制转换器的示例代码,可以实现十进制、二进制、八进制和十六进制之间的相互转换。其中,我们定义了一个 `Stack` 类来实现栈的基本操作,然后分别实现了将十进制转换为二进制、八进制和十六进制的函数 `decimal_to_binary`、`decimal_to_octal` 和 `decimal_to_hexadecimal`,以及将二进制、八进制和十六进制转换为十进制的函数 `binary_to_decimal`、`octal_to_decimal` 和 `hexadecimal_to_decimal`。
阅读全文