如何计算一个数在二进制中1的个数
方法一
按位右移:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
unsigned int x;
scanf("%d", &x);
int count = 0;
while (x) {
if (x & 1) {
count++;
}
x >>= 1;
}
printf("%d\n", count);
system("pause");
return 0;
}
方法二
减一操作实现:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
unsigned int x;
scanf("%d", &x);
int count = 0;
while (x) {
x &= (x - 1);
count++;
}
printf("%d\n", count);
system("pause");
return 0;
}