Dado un número decimal como entrada, la tarea es escribir un programa Python para convertir el número decimal dado en un número binario equivalente.
Ejemplos:
Input : 7 Output :111 Input :10 Output :1010
Método #1: solución recursiva
Python3
# Function to convert decimal number # to binary using recursion def DecimalToBinary(num): if num >= 1: DecimalToBinary(num // 2) print(num % 2, end = '') # Driver Code if __name__ == '__main__': # decimal value dec_val = 24 # Calling function DecimalToBinary(dec_val)
Python3
# Python program to convert decimal to binary # Function to convert Decimal number # to Binary number def decimalToBinary(n): return bin(n).replace("0b", "") # Driver code if __name__ == '__main__': print(decimalToBinary(8)) print(decimalToBinary(18)) print(decimalToBinary(7))
Python3
# Python program to convert decimal to binary # Function to convert Decimal number # to Binary number def decimalToBinary(n): return "{0:b}".format(int(n)) # Driver code if __name__ == '__main__': print(decimalToBinary(8)) print(decimalToBinary(18)) print(decimalToBinary(7))
Python3
# Quick Ninja One line Code print(bin(4785)[2:])
Python3
# Use this for user input #decNum = int(input("Enter any Decimal Number: ")) decNum = 4785 print(bin(decNum)[2:]) decNum1 = 10 print(bin(decNum1)[2:]) decNum2 = 345 print(bin(decNum2)[2:])