我想知道如何将十进制转换为二进制

时间:2019-09-28 12:00:01

标签: python

我有一个问题。 我不知道为什么我的代码是错误的

def binary_converter(decimal_number):

     i = decimal_number
     result = ''
         while i >= 0 :
             if i % 2 == 0:
                 result =  result + "0"
                 i = i/2
             else :
                result = "1"
                  i = i/2

     return result.strip()

这是我的代码。怎么了?

1 个答案:

答案 0 :(得分:1)

您的代码中几乎没有小错误,请参阅以下注释以获取详细信息:

def binary_converter(decimal_number):
    if decimal_number==0:           #corner case
        return "0";

    i = decimal_number
    result = ""

    while i>0:                      # while i >= 0 : //your loop was running indefinitely
        if i % 2 == 0:
            result =  result + "0"
            i = i//2                # i= i/2 was doing exact division for eg. 3/2=1.5 but 3//2=1
        else :
            result = result + "1"   # there was a silly mistake here
            i = i//2
    return result[::-1].strip()     # ans should be reversed before converting to integer