思路:二进制不同位,直接采用异或,然后采用循环右移计算1的个数即可。
Java:
public class Solution {
public int countBitDiff (int m, int n) {
int c = m^n;
int count = 0;
while(c != 0){
count += c & 1;
c = c >> 1;
}
return count;
}
}
C++:
class Solution {
public:
int countBitDiff(int m, int n) {
int count = 0;
m = m ^ n;
for(int i = 0; i < 32; ++i){
count += (m >> i) & 1;
}
return count;
}
};