daixinet

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

问题:编程实现将一个N进制数转换成M进制数。(c/c++、Java、Javascript、C#、Python)

1、Python 手写算法版

def conversion_num(num, src, dest):
    rtn = ''
    # 1、校验源和目标是否相同
    if src == dest:
        rtn = num
    # 2、转成10进制#
    if src != 10:
        num_str = str(num)
        num_str = num_str[::-1]
        exe_num = 0
        dec_num = 0
        for num_char in num_str:
            # 十六进制处理
            if num_char == 'A':
                num_char = '10'
            elif num_char == 'B':
                num_char = '11'
            elif num_char == 'C':
                num_char = '12'
            elif num_char == 'D':
                num_char = '13'
            elif num_char == 'E':
                num_char = '14'
            elif num_char == 'F':
                num_char = '15'

            num_int = int(num_char)
            if exe_num == 0:
                dec_num += num_int
            else:
                dec_num += src ** exe_num * num_int
            exe_num += 1
        num = dec_num
    # 3、转成目标进制
    if dest == 10:
        rtn = num
    else:
        num = int(num)
        while True:
            divisor = num // dest
            remainder = num % dest
            # 十六进制处理
            if remainder == 10:
                remainder = 'A'
            elif remainder == 11:
                remainder = 'B'
            elif remainder == 12:
                remainder = 'C'
            elif remainder == 13:
                remainder = 'D'
            elif remainder == 14:
                remainder = 'E'
            elif remainder == 15:
                remainder = 'F'
            rtn = str(remainder) + rtn
            if divisor <= 0:
                break
            else:
                num = divisor
    # 4、处理空的字符串
    if rtn == '':
        rtn = '0'
    return rtn


new_num = conversion_num('111111', 2, 16)
print(new_num) 

2、python内部方法版:

def conversion_num(num, src, dest):
    rtn = ''
    # 1、校验源和目标是否相同
    if src == dest:
        rtn = num
    # 2、转成10进制#
    if src != 10:
        dec_num = 0
        if src == 2:
            dec_num = int(num, 2)
        elif src == 8:
            dec_num = int(num, 8)
        elif src == 16:
            dec_num = int(num, 16)
        num = dec_num
    # 3、转成目标进制
    if dest == 10:
        rtn = num
    else:
        if dest == 2:
            rtn = bin(num)
        elif dest == 8:
            rtn = oct(num)
        elif dest == 16:
            rtn = hex(num)
    # 4、处理空的字符串
    if rtn == '':
        rtn = '0'
    return rtn


new_num = conversion_num('111111', 2, 16)
print(new_num)

 3、

 

posted on 2018-05-23 14:49  daixinet.com  阅读(3691)  评论(0编辑  收藏  举报