蓝桥杯年号字串

题目

小明用字母 A 对应数字 1,B 对应 2,以此类推,用 Z 对应 26。对于 27 以上的数字,小明用两位或更长位的字符串来对应,例如 AA 对应 27,AB 对 应 28,AZ 对应 52,LQ 对应 329。 请问 2019 对应的字符串是什么?

题解

看到许多题解用到了%取余,这样虽说可以解这个题,但是会在处理26、52 这类26的倍数时会出错。

for i in [25, 26, 27, 51, 52, 53]:
    n = i
    res = []
    while n > 0:
        n, x = divmod(n, 26)
        res.append(x)
    res = [*map(lambda x: chr(64 + x), res)][::-1]
    print(i, ''.join(res))

image

于是我们采取最笨的方法进行进制计算,每27进1

def into(arr):
    arr = [arr]
    carry = 1
    while arr[-carry] >= 27:
        num = arr[-carry]
        k = 0
        while num >= 27:
            k += 1
            num -= 26
        arr[-carry] = num
        arr.insert(0, k)
        carry += 1

    return ''.join([chr(ord("A") + i - 1) for i in arr])

image

posted @ 2022-04-05 11:08  幻非  阅读(84)  评论(0)    收藏  举报