Python:试图在整数中计算1位数量,但缺少一个1
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
I think I'm misunderstanding some concepts here. Would appreciate some guidance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
python
3.10
介绍但是,如果您必须自己实现算法,则可以尝试这样的事情:test.py:
test:
该算法的时间复杂性是
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:
Test:
The time complexity of this algorithm is
O(k)
wherek
is the number of bits set to 1.将
str(n)
更改为bin(n)[2:]
。这样,您将获得n
的二进制表示字符串,并省略“ 0b”前缀。顺便说一句,您无需在循环中手动计数。 Python字符串具有
.count()
:change
str(n)
intobin(n)[2:]
. This way you will get binary representation string ofn
with omitted "0b" prefix.BTW, you don't need to count manually in a loop. Python string has
.count()
: