十进制数转二进制数问题(Python)

Conversion of denary number to binary number problem (Python)

我遇到了一个问题,我必须编写一个函数,使用重复除以二算法将二进制数转换为二进制数。步骤包括:

请点击下面的 link 查看输出结果: https://i.stack.imgur.com/pifUO.png

def dentobi(user):
  denary = user
  divide = user / 2
  remainder = user % 2
  binary = remainder
  
  if user != 0:
    print("Denary:", denary)
    print("Divide by 2:", divide)
    print("Remainder:", remainder)
    print("Binary:", binary)
  
user = int(input("Please enter a number: "))
dentobi(user)

这是我到目前为止所做的,但我没有取得任何进展。

谁能解释一下我会怎么做?

一种方法,使用divmod除以2一步求余数:

def binary(num):
    b = ""
    while num:
        num, digit = divmod(num, 2)
        b = f"{digit}{b}"
    return b

binary(26)
'11010'

这假设一个正数,但可以很容易地扩展到 0 和负数。

@user2390182 提供的答案在功能上是正确的,除了当 num 为零时它 returns 是一个空字符串。但是,我多次注意到 divmod() 相当慢。以下是三种略有不同的技术及其性能统计数据。

import time

# This is the OP's original code edited to allow for num == 0
def binaryx(num):
    b = ""
    while num:
        num, digit = divmod(num, 2)
        b = f"{digit}{b}"
    return b or '0'

# This is my preferred solution
def binaryo(n):
    r = []
    while n > 0:
        r.append('1' if n & 1 else '0')
        n >>= 1
    return ''.join(reversed(r)) or '0'

# This uses techniques suggested by my namesake
def binaryy(n):
    r = ''
    while n > 0:
        r = str(n & 1) + r
        n >>= 1
    return r or '0'

M = 250_000

for func in [binaryx, binaryo, binaryy]:
    s = time.perf_counter()
    for _ in range(M):
        func(987654321)
    e = time.perf_counter()
    print(f'{func.__name__} -> {e-s:.4f}s')

输出:

binaryx -> 1.3817s
binaryo -> 0.9861s
binaryy -> 1.6052s