461. Hamming Distance

1. 題目鏈接:

https://leetcode.com/problems/hamming-distance/

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.</pre>

2. 題目關鍵詞

  • 難度等級:easy
  • 關鍵詞:
  • 語言: C/C++

3. 解題思路

使用異或運算,然后統(tǒng)計異或結果中數(shù)字 1 的個數(shù)。

int hammingDistance(int x, int y){
    
    // 返回hamming距離
    int num = 0;
    
    int result = x ^ y; // 異或預算
    
    while (result != 0) { // 統(tǒng)計result中1的個數(shù)
        int tmp = result & 1; // 取最低位
        if (tmp == 1) {
            num++;
        }
        result = result >> 1;
    }

    return num;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容