LeetCode筆記:461. Hamming Distance

問題(Easy):

TheHamming distancebetween two integers is the number of positions at which the corresponding bits are different.
Given two integersxandy, calculate the Hamming distance.
Note:
0 ≤x,y< 231.
Example:

Input: x = 1, y = 4
Output: 2
Explanation:



The above arrows point to positions where the corresponding bits are different.

大意:

兩個數之間的漢明距離是指其比特位的不同的個數。
給出兩個整數x和y,計算漢明距離。
注意:
0 ≤x,y< 231.
例子:

輸入: x = 1, y = 4
輸出: 2
解釋:



上面的箭頭指向的位置就是比特位不同的地方。

思路

題目很簡單,就是比較兩個數字的比特位不同之處,那就從右到左一個個比較就好了,也就是要從右往左一個個比較每比特位數字是否相同。因為實際上整數在計算機中就是以二進制存儲的,所以可以用右移操作符來操作,更直白的也可以不斷地除以2來右移,同時對2取模來得到每次最右邊的那個數字,看看兩個數取模得到的數是否一樣,不一樣則距離加一。需要注意的就是每次除以2時要判斷數字是否已經變成0了,同樣的方式判斷循環是否終止。

代碼(C++):

class Solution {
public:
    int hammingDistance(int x, int y) {
        int x1,y1,res = 0;
        while (x > 0 || y > 0) {
            x1 = x % 2;
            y1 = y % 2;
            if (x1 != y1) res++;
            
            if (x > 0) x = x / 2;
            if (y > 0) y = y / 2;
        }
        return res;
    }
};

他山之石:

用異或這個位操作符就可以記錄下兩個數字所有比特位不同的地方,然后同樣的一個個去記錄不同的個數,這里他用了一種很巧妙的方式,自己距離推演一下就知道怎么有效的了。

class Solution {
public:
    int hammingDistance(int x, int y) {
        int dist = 0, n = x ^ y;
        while (n) {
            ++dist;
            n &= n - 1;
        }
        return dist;
    }
};

合集:https://github.com/Cloudox/LeetCode-Record


查看作者首頁

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容