Number of 1 Bits
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.
方法一:
从右向左依次将n的二进制与1进行&(与运算);当一次结果为1时利用i将其记录下来;
其中的:
int n = 7;//二进制为111
n >> 1;
cout << n;//输出3(二进制为11)
是将n的二进制向右移一位;
(n >>= 1;
等价于
n = n >> 1)
#include<iostream>
#include"inttypes.h"
using namespace std;
int hammingWeight(uint32_t n) {
int i = 0;
while( n > 0)
{
i += n & 0x1;
n >>= 1;
}
return i;
}
int main(){
int n;
int x;
x = hammingWeight( n );
cout << x;
}
方法二:
思路:每次n&(n-1)可以将n里面的值为1的位数减少一位
int i= 0;
6 = 7 & 6 即:110 = 111 & 110;i = 1
4 = 6 & 5 100 = 110 & 101;i = 2
0 = 4 & 3 000 = 100 & 011;i = 3
#include<iostream>
#include"inttypes.h"
using namespace std;
int hammingWeight(uint32_t n) {
int i = 0;
while( n > 0){
n &= n - 1;
i++;
}
return i;
}
int main(){
int n;
int x;
cin >> n;
x = hammingWeight( n );
cout << x;
}