两个知识点:用位运算异或,两个数异或相同为0,不同为1.得到结果再去求1的个数 class Solution { public: int countBitDiff(int m, int n) { int count=0; int val=m^n; while(val) { count++; val=val&(val-1); } return count; } };
class Solution { public: // 存放int整数的二进制的32位 vector<int> getBinary(int x) { vector<int> xBinary; for(int i=0; i<32; i++) { do{ xBinary.push_back(x%2); }while(x/=2); if(x/2==0) { xBinary.push_back(0); } } return xBinary; } // 32位每位进行对比 int countBitDiff(int m, int n) { int count=0; vector<int> mBinary, nBinary; mBinary = getBinary(m); nBinary = getBinary(n); for(int i=0; i<32; i++) { if(mBinary[i]!=nBinary[i]) { count+=1; } } return count; } };
class Solution { public: int countBitDiff(int m, int n) { int count = 0; while(m||n){//当有一者为0后,0%2=0,相当于给不够位补零了。 if(m%2 != n%2) count++; m /= 2; n /= 2; } return count; } }; /*排行第一的思路很精妙,异或运算将两个数中不同位标注为1,在通过按位与运算,统计1的个数,即不同位 个数。不过这种代码浓缩度高,不见得时间复杂度小,按位与运算计算机执行要比普通加减乘除复杂,需要每一位比较。不过思路还是值得学习。*/ class Solution { public: int countBitDiff(int m, int n) { int mn,count = 0; mn = m^n;//异或,相同会变0,不同会变1,和数学上有区别,这里是按二进制每位进行异或处理。 while( mn != 0 ){//不为零说明其中有1存在,而1的个数正是两个数二进制位不同的个数。 mn &= (mn-1);//mn = mn&(mn-1),mn-1即将以最末尾的1变成了零。而&运算为按位与运算,两者相同位都为1,才为1,每次除去最末尾的1。 count++; } return count; } };
class Solution { public: /** * 获得两个整形二进制表达位数不同的数量 * * @param m 整数m * @param n 整数n * @return 整型 */ int countBitDiff(int m, int n) { int diffs = 0; int xornum = m^n; while(xornum){ if((xornum & 0x80000000) == 0x80000000){ diffs ++; } xornum <<= 1; } return diffs; } };
public class Solution { /** * 获得两个整形二进制表达位数不同的数量 * * @param m 整数m * @param n 整数n * @return 整型 */ public int countBitDiff(int m, int n) { int tmp=m^n; if(tmp==0) return 0; int count=0; while(tmp!=0){ count++; tmp=tmp&(tmp-1); } return count; } }