【问题标题】:Efficient code to count the number of trailing 0s at the end of a binary number计算二进制数末尾尾随 0 数量的有效代码
【发布时间】:2021-08-09 03:42:48
【问题描述】:

我正在研究一种在二进制数中查找尾随零数量的方法,并在 C (link) 中找到了一个解决方案。我正在寻找 Python 中的解决方案!

Binary Input -> 1000
Output: 3

Binary Input -> 101101001100
Output: 2

Binary Input -> 1010001010000
Output: 4

Binary Input -> 100000001
Output: 0

有没有一种有效的方法可以做到这一点,而无需将二进制数作为字符串进行迭代或使用字符串方法进行过滤?基本上,我可能有大量非常非常大的二进制数,所以我试图找到比简单地将其作为字符串迭代更有效的方法。


编辑:

这是我的尝试-

def trailingzeros(l):
    count = 0
    a = [i for i in str(l)]
    for i in reversed(a):
        if i=='0':
            count+=1
        else:
            break
    return count

注意:我正在寻找一种利用输入的二进制性质的解决方案。

【问题讨论】:

标签: python string list


【解决方案1】:
n = 0b1010001010000

count = 0
while n:
    if (n&1):
        break
    n >>= 1
    count += 1

print(count)

打印:

4

【讨论】:

  • 此解决方案使用二进制和 (n & 1) 和移位 (n >>=1),它们已与 Python 一样优化。 +1
  • 感谢这项工作。我正在寻找可以利用的二进制操作而不是字符串操作。
【解决方案2】:

你可以使用python位运算符:

def findTrailing0(num):
    count = 0
    lastBit = 0
    while num != 0:
        lastBit = num & 0x1
        if lastBit != 0:
            break
        count += 1
        num >>= 1
    return count

【讨论】:

  • 感谢您的解决方案,这与@andrej 之前的回答是否存在逻辑差异。
  • 没有。基本上是一样的解决方案。
猜你喜欢
  • 2011-12-10
  • 1970-01-01
  • 2022-12-18
  • 2019-06-22
  • 2018-11-06
  • 1970-01-01
  • 2017-09-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多