pygorithm/stack/number_conversion.py

25 lines
522 B
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""
进制转换:
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