25 lines
522 B
Python
25 lines
522 B
Python
"""
|
||
进制转换:
|
||
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
|