求二進(jìn)制數(shù)中1的個(gè)數(shù) - 博客園
普通法
n & 1 得到 n 的最后一個(gè)數(shù)字,然后移位判斷每一位數(shù)字。
比如 n = 250,n & 1 的結(jié)果前7位都是0,所以 n & 1 = n 的最后一位數(shù)字
250 11111010
1 00000001
// 普通法
int count1(unsigned int n) {
int count = 0;
while (n > 0) {
if ((n & 1) == 1) count++; // 判斷n的二進(jìn)制最后一位是不是1
n >>= 1; // 數(shù)據(jù)右移一位
}
return count;
}
int count0(unsigned int n) {
int count = 0;
while (n > 0) {
if ((n & 1) == 0) count++; // 判斷n的二進(jìn)制最后一位是不是1
n >>= 1; // 數(shù)據(jù)右移一位
}
return count;
}
快速法
快在不用逐個(gè)位比較,最后 count 值就是需要 while 循環(huán)的次數(shù)。原理如下:
n = n & (n - 1); // 1換0
n = n | (n + 1); // 0換1
比如 n = 7
n 7 0111
n-1 6 0110 n & (n - 1) = 0110
n+1 8 1000 n | (n + 1) = 1111
// 快速法
int count1(unsigned int n) {
int count = 0;
while (n > 0) { // 所有1都換成0跳出循環(huán)
n = n & (n - 1); // 1換0
count++;
}
return count;
}
int count0(unsigned int n) {
int count = 0;
while (n != 255) { // 所有0都換成1跳出循環(huán)
n = n | (n + 1); // 0換1
count++;
}
return count;
}
int main() {
unsigned int a = 250;
bitset<8> bs(a);
cout << bs << endl; // 二進(jìn)制
cout << count1(a) << endl;
cout << count0(a) << endl;
}
11111010
6
2