二进制扩展求二进制中1 的个数 及扩展问题

最近朋友几篇文章介绍了改二进制扩展的文章. 关联文章的地址

#include<stdio.h>
/*
  求num 二进制中1 的个数,复杂度为o(count) ,
  num&(num-1) 每次清除右起第一个1
  斟酌 num=1110 
     num-1=1101
     num&(num-1)=1100
*/   
int numCount(int num)
{
   int count = 0;
   while(num)
   {
      num&=(num-1); // 将num 右起第一个 1 给清除掉  
      count++;
   }    
   return count;
}
int main()
{
  int num;
  while(scanf("%d",&num)!=EOF)
  printf("%d\n",numCount(num));

  return 0;
}

    

    扩展问题2

    每日一道理
自己把自己说服了,是一种理智的胜利;自己被自己感动了,是一种心灵的升华;自己把自己征服了,是一种人生的成功。
#include<stdio.h> 
/*
  给定两个整数A,B ,那么把A变成B需要转变多少位(bit)  ?
  也是求A B 的二进制的情势有多少不同的
  那么将A ,B 异或之后得到C ,求C的二进制中有多少个1(雷同的0) 
*/

int numChange(int A,int B)
{
    int C = A^B;
 
    int count=0;
    while(C)   
    {
       C &= (C-1) ;
       count++;
    }
    return count;
}
int main()
{
    int A ,B;
    while(scanf("%d %d",&A,&B)!=EOF)
    {
       printf("%d\n",numChange(A,B));
    }
    return 0;
}

文章结束给大家分享下程序员的一些笑话语录: 联想——对内高价,补贴对外倾销的伟大“民族”企业。

--------------------------------- 原创文章 By
扩展和问题
---------------------------------

posted @ 2013-05-30 20:30  坚固66  阅读(206)  评论(0)    收藏  举报