题目:
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’的个数。
解答:
这里我先最简单的循环除以二看余数是否为2
int hammingWeight2(uint32_t n) {
int count=0;
while(n){
if(n%2==1)count++;
n/=2;
}
return count;
}
当然这类题一定也会有位运算的方法了~并且这种方法导方法才是主导
int hammingWeight(uint32_t n) {
int count=0;
while(n){
count+=n&1;
n=n>>1;//这个和n/=2;效果一致,>>表示二进制数x向右移一位
}
return count;
}
我还在网上找到了至少比我的聪明的方法:
int hammingWeight(uint32_t n) {
int count=0;
while(n){
n&=n-1;
count++;
}
return count;
}