题目描述
解题思路
本题思路就是求两个2进制数1的不同个数,可以先进行相与,再统计1的个数。
此时统计1的个数也就可以使用上一题比特位计数的方法。
// Brian Kernighan 算法public int hammingDistance(int x, int y) {x ^= y;int count = 0;while (x != 0) {x &= (x - 1);count++;}return count;}
移位
// 移位统计1public int hammingDistance(int x, int y) {x ^= y;int count = 0;while (x != 0) {if ((x & 1) == 1) count++;x >>= 1;}return count;}
