【问题标题】:How many 1 bit can be found in the binary form of multiplication of two numbers?两个数相乘的二进制形式可以找到多少个 1?
【发布时间】:2022-04-07 23:20:33
【问题描述】:

我在测试中发现了这个问题,但无法解决:给定两个任意数字,如何在不计算乘积本身的情况下计算其乘积二进制表示中的1 位的数量?解的渐近复杂度必须是O(log(A+B)),其中AB 是给定的因子。

例如,如果 AB37,则产品是 2121的二进制表示是10101,它有三个1位,所以答案是3

谁能建议如何做到这一点?

【问题讨论】:

  • @JohnBollinger 绝对不是
  • @harold 怎么不行?您计算产品,并计算其中设置的位。对于给定的数据类型,可以在恒定的时间和空间内完成位计数,这甚至比所要求的复杂度界限还要好。
  • @JohnBollinger 如果这是答案,OP 早就知道了。另外数据类型不能是定长的,否则整个问题一开始就不存在。
  • @John Bollinger:请参阅编辑。

标签: binary numbers bit


【解决方案1】:

我在一次面试中被问到同样的问题,这是我提交的,所有的测试用例都通过了。我希望这是您正在寻找的解决方案。 内置函数 bin(n) 的复杂度为 O(log(n)),count() 函数的复杂度为 O(n) 此代码在 Python3 中:

    def checkBinSet(a, b):
        output = a*b
        if output == 0:   # when the product is 0 just return 0
            return 0
        else:   
            binResult = bin(output)[2:]  # in this case bin(n) returns output as '0b10101', remove the 0b from the output using [2:], you will get the binary bits only '10101'
            return binResult.count("1")  # looking for the count of 1s in the binResult. You can also replace the count() function using loop and then count the number of 1s and increase the counter
    result = checkBinSet(3,7)
    print(result)    # output is 3

【讨论】:

    猜你喜欢
    • 2019-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-21
    • 1970-01-01
    • 2011-06-09
    相关资源
    最近更新 更多