The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x
and y
,
calculate the Hamming distance.
Note:
0 ≤ x
, y
<
231.
Example:
Input: x = 1, y = 4 Output: 2 Explanation: 1 (0 0 0 1) 4 (0 1 0 0) ? ? The above arrows point to positions where the corresponding bits are different.
第一次寫的時候沒有想到位運算 ,
x%2 != y% 2;
sum ++;
x/=2;
y/=2;
效率不高,看別人的答案發現可以位運算,
複習一下 位運算 ,
^ 是 異或 運算 ,求解兩個2進制數不同的位的個數
&是 與 運算
>>n 右移n位,同除以2的n次方
例如 。 x & 1 則是求最後一位
特別地用法:
while (n >0 ) {
count ++;
n &= (n-1);
}
求解了 n 中 1的個數
也可以通過
while( n ){
if ( (n >>1) << 1 != n )
count ++;
n>>=1;
}
來計算n中1的個數
最主要的還是要第一下想起用位運算 z = x ^y, 然後求解z中1的個數。