Python

Using Python to convert decimal to binary number

Provided a decimal number as input, the challenge is to develop a Python program that converts the given decimal number into an equal binary number.

Examples:

Input: 13
Output: 1101

Recursive solution:

# Function to convert decimal number
# to binary using recursion

result = []
def decimal_to_binary(decimal):
    if decimal >= 1:
        decimal_to_binary(decimal // 2)
        result.append(decimal % 2) 
        return result

# call the functio 
decimal_to_binary(decimal)
print(result)
    

Convert decimal to binary using the built-in function

Python has a built-in function that we can use to convert decimal numbers to binary numbers.

def decimal_to_binary(decimal):
    return bin(decimal).replace("0b", "")

Convert decimal to binary without a built-in function

# Function to convert Decimal number
# to Binary number

def decimal_to_binary(decimal):
    return "{0:b}".format(int(decimal))