Python:试图在整数中计算1位数量,但缺少一个1

发布于 2025-02-03 01:26:50 字数 684 浏览 2 评论 0原文

Input: n = 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.

当我在下方运行代码时,似乎只有两个1被识别...为什么?

class Solution(object):
    def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        
        sum = 0
        
        for i in str(n):
            sum += int(i)
            
        return sum 

我认为我在这里误解了一些概念。感谢一些指导。

Input: n = 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.

When I run my code below it appears that only two 1's are recognized ... why is that?

class Solution(object):
    def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        
        sum = 0
        
        for i in str(n):
            sum += int(i)
            
        return sum 

enter image description here

I think I'm misunderstanding some concepts here. Would appreciate some guidance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

静赏你的温柔 2025-02-10 01:26:50

python 3.10介绍但是,如果您必须自己实现算法,则可以尝试这样的事情:

test.py:

def count(n):
    bits = 0

    while n:
        bits += 1
        n &= n - 1

    return bits


def main():
    n = 0b110001010000000000111
    c = count(n)

    print(f"Bit length: {n.bit_length()}, bits: {c}")


if __name__ == "__main__":
    main()

test:

$ python test.py
Bit length: 21, bits: 7

该算法的时间复杂性是o(k)其中k是设置为1的位数。

Python 3.10 introduces int.bit_count() but if you have to implement the algorithm yourself then you can try something like this:

test.py:

def count(n):
    bits = 0

    while n:
        bits += 1
        n &= n - 1

    return bits


def main():
    n = 0b110001010000000000111
    c = count(n)

    print(f"Bit length: {n.bit_length()}, bits: {c}")


if __name__ == "__main__":
    main()

Test:

$ python test.py
Bit length: 21, bits: 7

The time complexity of this algorithm is O(k) where k is the number of bits set to 1.

栖竹 2025-02-10 01:26:50

str(n)更改为bin(n)[2:]。这样,您将获得n的二进制表示字符串,并省略“ 0b”前缀。

顺便说一句,您无需在循环中手动计数。 Python字符串具有.count()

return bin(n).count("1")

change str(n) into bin(n)[2:]. This way you will get binary representation string of n with omitted "0b" prefix.

BTW, you don't need to count manually in a loop. Python string has .count():

return bin(n).count("1")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文