编写代码实现:求一个整数储存在内存中的二进制中1的个数
方法1:
int main() {
int n = 15;
int count = 0;
while (n) {
if (n % 2 == 1) {
count++;
}
n = n / 2;
}
printf("二进制中一的个数:%d\n", count);
system("pause");
return 0;
}
优化方法2:
int main() {
int n = -1;
int i = 0;
int count = 0;
for (i = 0; i < 32; i++) {
if (((n >> i) & 1) == 1) {
count++;
}
}
printf("二进制中一的个数:%d\n", count);
system("pause");
return 0;
}
优化方法3:
int main() {
int n = -1;
int i = 0;
int count = 0;
while (n) {
count++;
n = n & (n - 1);
}
printf("二进制中一的个数:%d\n", count);
system("pause");
return 0;
}