编写一个函数,确定需要改变几个位,才能将整数A转成整数B。

先异或,然后统计1的个数。

统计1的个数可以移位一位一位看,

高级的算法 n&(n-1)会消去n最低位的1.

 

扩展 n&(n-1)==0代表什么意思:n是2的某次方或者n==0;

 

int bitSwapRequired(int a,int b){
    int count=0;
    for(int c=a^b;c!=0;c>>1)
        count+=c&1;
    
    return count;
}

int bitSwapRequired2(int a,int b){
    int count=0;
    for(int c=a^b;c!=0;c=c&(c-1))
        count++;
    
    return count;
}

 

posted @ 2014-08-23 16:18  jdflyfly  阅读(280)  评论(0)    收藏  举报