漢明距離
兩個整數之間的漢明距離指的是這兩個數字對應二進制位不同的位置的數目。
給出兩個整數 x 和 y,計算它們之間的漢明距離。
思路:
當看到“對應二進制位不同的位置的數目“這句話的時候就可以想到用二進制計算中的異或運算
之后只要統計一下結果二進制表示中1的個數就行了,此時可以使用Integer中的 bitCount() 方法
查看了一下JavaApi,解釋如下
-
bitCount
public static int bitCount(int i)
-
Returns the number of one-bits in the two's complement binary representation of the specified
intvalue. This function is sometimes referred to as the population count.
作用是返回 i 的二進制表示中1的個數
也可以用我下面的方法統計
class Solution { public int hammingDistance(int x, int y) { int sum = x^y; int count; for(count = 0; sum > 0; count++){ sum &= (sum - 1); } return count; } }
原理是:每次for循環,都將sum的二進制中最右邊的 1 清除。
為什么呢?
因為從二進制的角度講,n相當於在n - 1的最低位加上1。舉個例子,8(1000)= 7(0111)+ 1(0001),
所以8 & 7 = (1000)&(0111)= 0(0000),清除了8最右邊的1(其實就是最高位的1,因為8的二進制中只有一個1)。
再比如7(0111)= 6(0110)+ 1(0001),所以7 & 6 = (0111)&(0110)= 6(0110),清除了7的二進制表示中最右邊的1(也就是最低位的1)。
