程序分析:
(1)将原数字每次右移一位,再和1作与操作。
(2)将原数字与原数字减一后的值作与操作。
C代码:
第一种:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int main() {
int num;
printf("Please input a number:");
scanf("%d", &num);
int count = 0;
while (num!=0) {
count++;
num &= num - 1;
}
printf("The count of number is:%d\n", count);
return 0;
}
第二种:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int main() {
int num;
printf("Please input a number:");
scanf("%d", &num);
int count = 0;
while (num!=0) {
if (num & 1) {
count++;
}
num = num >> 1;
}
printf("The count of number is:%d\n", count);
return 0;
}
C运行结果: