一、 正数如何输出1的个数
#include <stdio.h>
#include <stdlib.h>
int main(){
int i = 7;
int count = 0;
while (i != 0){
if (i % 2 == 1)
count++;
i = i / 2;//除二相当于去掉了二进制中的一个1;
}
printf("%d\n", count);
system("pause");
return 0;
}
二、任一个整数数中1的个数
#include <stdio.h>
#include <stdlib.h>
int count_one(int x)
{
int count = 0;
while (x){
count++;
x = x&(x - 1);//相当于取掉二进制的一个1;
}
return count;
}
int main()
{
int num = -1;
int i= count_one(num);
printf("%d\n", i);
system("pause");
return 0;
}
欢迎各位,批评指正。