📜  Python程序将十进制数转换为二进制数

📅  最后修改于: 2022-05-13 01:55:37.188000             🧑  作者: Mango

Python程序将十进制数转换为二进制数

给定一个十进制数作为输入,任务是编写一个Python程序将给定的十进制数转换为等效的二进制数。
例子 :

Input : 7                                                         
Output :111

Input :10
Output :1010

方法#1:递归解决方案

DecimalToBinary(num):
        if num >= 1:
            DecimalToBinary(num // 2)
           print num % 2 

下面是上述递归解决方案的实现:

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


输出
011000

方法#2:使用内置函数将十进制转换为二进制

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))
输出
1000
10010
111

方法#3:没有内置函数

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

输出

1000
10010
111