海明距離 Hamming Distance

問題:java

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.spa

Given two integers x and y, calculate the Hamming distance.code

Note:
0 ≤ xy < 2^31.遞歸

Example:ip

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.

解決:get

【注】題目要求的海明距離其實是指兩個二進制數對應位不相同的個數it

① 根據異或的性質:相同爲0,不一樣爲1。因此先求出異或的結果,而後計算結果中1的個數。io

class Solution { // 11ms
    public int hammingDistance(int x, int y) {
        if(x == y) return 0;
        int count = 0;
        int tmp = x ^ y;
        while(tmp != 0){
            tmp = tmp & (tmp - 1);
            count ++;
        }
        return count;
    }
}class

② 直接調用java中的方法計算1的個數。二進制

class Solution { // 15ms
    public int hammingDistance(int x, int y) {
        return Integer.bitCount(x ^ y);
    }
}

③ 在網上看到一種遞歸的寫法,遞歸終止的條件是當兩個數異或爲0時,代表此時兩個數徹底相同。咱們返回0,不然咱們返回異或和對2取餘加上對x>>1和y>>1調用遞歸的結果。異或和對2取餘至關於檢查最低位是否相同而對x>>1和y>>1調用遞歸至關於將x和y分別向右移動一位,這樣每一位均可以比較到,也能獲得正確結果。

class Solution { // 10ms     public int hammingDistance(int x, int y) {         if((x ^ y) == 0) return 0;         return (x ^ y) % 2 + hammingDistance(x >> 1,y >> 1);     } }

相關文章
相關標籤/搜索