July 11, 2022 | Posted in Python
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
# 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)
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", "")
# Function to convert Decimal number
# to Binary number
def decimal_to_binary(decimal):
return "{0:b}".format(int(decimal))