Leetcode題解之其他(2)漢明距離
阿新 • • 發佈:2018-12-02
題目:https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/26/others/65/
題目描述:
漢明距離
兩個整數之間的漢明距離指的是這兩個數字對應二進位制位不同的位置的數目。
給出兩個整數 x
和 y
,計算它們之間的漢明距離。
注意:
0 ≤ x
, y
< 231.
示例:
輸入: x = 1, y = 4 輸出: 2 解釋: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ 上面的箭頭指出了對應二進位制位不同的位置。
思路:可以對X 和Y進行異或運算 得到temp 。然後計算temp 位為1 的個數。這裡還利用了temp=temp&temp-1 的技巧 統計位為1的個數。比如: temp =1011 temp-1 = 1010 , temp&temp-1 = 1010 count +1 ;
temp = 1010 temp-1 = 1001 , temp&temp-1 = 1000 count+1;
temp = 1000 temp -1 = 0111 , temp&temp-1 =0000 count +1; temp =0 結束。剛好count 為 temp位為1的個數
程式碼:
class Solution { public int hammingDistance(int x, int y) { int res = 0; int temp = x ^ y; while (temp!= 0) { res ++; temp &= (temp - 1); } return res; } //另外的方法 public int hammingDistance3(int x, int y) { int res = 0; String s1 = Integer.toBinaryString(x); String s2 = Integer.toBinaryString(y); int len1 = s1.length(); int len2 = s2.length(); while (len1 > len2) { s2 = "0" + s2; len2++; } while (len1 < len2) { s1 = "0" + s1; len1++; } char[] a = s1.toCharArray(); char[] b = s2.toCharArray(); for (int i = 0; i < len1; i++) { if (a[i] != b[i]) { res++; } } return res; } public static void main(String[] args) { System.out.println(hammingDistance1(7,8)); } }