打印出一个整数二进制包含1的个数

来源:互联网 发布:人族捏脸数据导入图 编辑:程序博客网 时间:2024/05/29 15:02
#include    <stdio.h>int binaryNum(int x){    int count = 0;    while( x )    {count ++;x = x & (x - 1);    }    return count;}int main(void){    printf("%d\n",binaryNum(9999999));    return 0;}


打印的结果是14,表明9999999二进制有14个1.


方法二:

#include    <stdio.h>int binaryNum(int x){    int count = 0;    while( x )    {       if(x & 1)       {              count ++;       }       x = x >> 1;    }    return count;}int main(void){    printf("%d\n",binaryNum(9999999));    return 0;}

int bitcount(unsigned x){    int b;    for( b= 0 ; 0 != x ; x >>= 1 )    {if( x & 01 ){    b ++;}    }        return b;}


原创粉丝点击