【问题标题】:Most efficient way to check if only one '1' exists in binary representation of a decimal number [duplicate]检查十进制数的二进制表示中是否仅存在一个“1”的最有效方法[重复]
【发布时间】:2019-11-10 04:29:19
【问题描述】:

在不使用特殊函数(数学、numpy 等)的情况下,检查十进制数在其二进制表示中是否只有一个“1”的最有效(就速度和空间而言)方法是什么?

例如1 是“001”,4 是“100”。

我试过了

binary  =  "{0:b}".format(value)
if binary.count('1') != 1:
    return 1
else:
    return 0

我相信这在空间方面是 O(log n),在速度方面是 O(n)?有没有办法更有效地做到这一点?

【问题讨论】:

  • 你说的是整数还是浮点数?
  • 只是整数值
  • 也许是math.log2(value).is_integer()
  • 根据@awesoon 的链接:(x != 0) and ((x & (x - 1)) == 0) 与使用math.log2() 一样快
  • math.log2 由于使用浮点数而失去精度,因此对于足够接近 2 的大幂的整数会产生误报。

标签: python-3.x


【解决方案1】:

其中一种方法可能是-

binary_num = '00101010'
result = [1 for x in binary_num if x == '1']
if len(result) == 1:
    print('Success')
else:
    print('Failed')

【讨论】:

    猜你喜欢
    • 2021-07-24
    • 1970-01-01
    • 2014-11-14
    • 1970-01-01
    • 2020-03-23
    • 2012-01-02
    • 1970-01-01
    • 2021-10-26
    • 2020-10-21
    相关资源
    最近更新 更多