pygorithm/stack/number_conversion.py

25 lines
522 B
Python
Raw Permalink Normal View History

2023-11-29 19:31:30 +08:00
"""
进制转换
1. 将十进制转换为二十六进制
2. 对2取余余数存入栈中
3. 将取余得的商重复第2步直到商为零
4. 将栈中的数取出即是转换为二进制的结果
"""
from .stack import Stack
def decimal_to_any(num: int, base: 2 | 8 | 16) -> str:
stack = Stack[str]()
while num > 0:
mod: int = num % base
num //= base
stack.push(str(mod))
res = ''
while not stack.is_empty():
res += stack.pop()
return res