Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011
, so the function should return 3.
写一个函数操作无符号整数,返回整数的二进制数1的个数。
解法:位操作Bit Manipulation
使用n&(n-1)的方法
假使 n =0x110101
n n-1 n&(n-1)
step1: 110101 110100 110100
step2: 110100 110011 110000
step3: 110000 101111 100000
step4: 100000 011111 000000
发现有几个1,就循环几次n&(n-1)得到0。
时间复杂度:O(M),M是n中1的个数
Java:
public class Solution {
public int NumberOf1(int n) {
int count = 0;
while (n != 0) {
n &= (n - 1);
count ++;
}
return count;
}
}
Python:
class Solution:
# @param n, an integer
# @return an integer
def hammingWeight(self, n):
result = 0
while n:
n &= n - 1
result += 1
return result
Python:
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
res=0
while n:
res += (n&1)
n >>= 1
return res
Python:
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
b = bin(n)
return b.count('1')
C++:
class Solution {
public:
int hammingWeight(uint32_t n) {
int res = 0;
for (int i = 0; i < 32; ++i) {
res += (n & 1);
n = n >> 1;
}
return res;
}
};
C++:
class Solution {
public:
int hammingWeight(uint32_t n) {
int count = 0;
for (; n; n &= n - 1) {
++count;
}
return count;
}
};
类似题目:
[LeetCode] 190. Reverse Bits 翻转二进制位