题解 | #进制转换#

进制转换

https://www.nowcoder.com/practice/8f3df50d2b9043208c5eed283d1d4da6

常规解法1:

hexadecimal = input()

maped = {
    "A": 10,
    "a": 10,
    "B": 11,
    "b": 11,
    "C": 12,
    "c": 12,
    "D": 13,
    "d": 13,
    "E": 14,
    "e": 14,
    "F": 15,
    "f": 15,
}


def cal_hex_to_int(hex_str: str):
    handle = hex_str.split("0x")[1]
    res = 0

    handle_len = len(handle)
    for i, v in enumerate(handle):
        map_v = maped.get(v, None)
        if map_v:
            res += map_v * pow(16, handle_len - i - 1)
        else:
            res += int(v) * pow(16, handle_len - i - 1)

    return res


print(cal_hex_to_int(hexadecimal))

解法2: 内置函数int转指定进制

hexadecimal = input()

print(int(hexadecimal), 16)

全部评论

相关推荐

kyw_:接好运
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务