简体   繁体   中英

i want to know how to convert decimal to binary

i have a question. i don't know why my code is wrong

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()

it is my code. what is wrong?

There were few little mistakes in your code, olease refer to comments below for details:

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

You can use built-in function Like

def decimalToBinary(n):  
    return bin(n).replace("0b", "")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM