题解 | #进制转换#

进制转换

https://www.nowcoder.com/practice/ac61207721a34b74b06597fe6eb67c52

import re
import sys

inputs = []
for line in sys.stdin:
    inputs.extend(list(map(int, line.split())))

def transfer_them(source, target):
        
    if target <= 1:
        raise ValueError("Target base must be greater than 1.")
    
    flag = ""
    if source < 0:
        source = -source
        flag = "-"
    
    result = []

    if source >= target:
        while source > 0:
            result.append(source % target)
            source //= target
        
        result.reverse()

    else:
        result.append(source)
    
    for index, item in enumerate(result):
        if item >= 10:
            result[index] = chr(item - 10 + ord('A'))
        else:
            result[index] = str(item)

    return flag + ''.join(result)

print(transfer_them(inputs[0], inputs[1]))

全部评论

相关推荐

11-24 11:23
门头沟学院 C++
点赞 评论 收藏
分享
11-08 17:36
诺瓦科技_HR
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务