您的位置:首页 > 理论基础

在计算机中,输出一个整数二进制中1的个数.

2017-04-14 20:50 127 查看
一、 正数如何输出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;
}

欢迎各位,批评指正。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐