首页 > 解决方案 > 将整数转换为具有尽可能少字符的字母数字字符串

问题描述

我正在寻找一种将十进制整数表示形式减少为字符数最少的字符串的方法。

例如,十六进制在十进制数字的顶部使用字母 AF。

hex(123)

有没有一种平滑的方法可以利用所有字母来进一步减少字符串长度?

标签: pythonintegerrepresentation

解决方案


这样您就可以使用自己的字母表,甚至可以将其扩展为 0-9、AZ、az:

递归:

BS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def to_base(n, b): 
  if not n: return "0"
  return to_base(n//b, b).lstrip("0") + BS[n%b]

迭代:

BS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def to_base(n, b):
    res = ""
    while n:
        res+=BS[n%b]
        n//= b
    return res[::-1] or "0"

注意:递归版本可以提高RuntimeError: maximum recursion depth exceeded in cmp非常大的整数和负数。

编码器用法: 参数(n,b)均值(要转换的数字,要使用的基数),例如:

>>> to_base(123,2)
'1111011'
>>> to_base(123,16)
'7B'
>>> to_base(123,len(BS))
'3F'
>>> to_base(1234567890000,16)
'11F71FB0450'
>>> to_base(1234567890000,len(BS))
'FR5HUGK0'

使用 len(BS) 意味着您将使用 BS 变量中的所有字符作为转换的基础。

迭代解码器:

def to_dec(n, b):
    res = 0
    power = 1
    for letter in enumerate(n[::-1]):
        i = BS.find(letter)
        res += i*power
        power *= b
    return res

解码器用法: 参数 (n, b) 均值(要转换的数,要使用的基数),例如:

>>> to_dec('1111011',2)
123
>>> to_dec('7B',16)
123
>>> to_dec('3F',len(BS))
123
>>> to_dec('11F71FB0450',16)
1234567890000
>>> to_dec('FR5HUGK0',len(BS))
1234567890000

希望这很有用;)

编辑:添加编码器使用
编辑:添加解码器
编辑:添加解码器使用


推荐阅读