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
xandy, 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;
}