编写一个函数,确定需要改变几个位,才能将整数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;
}
原文地址:https://www.cnblogs.com/jdflyfly/p/3931412.html