天天看點

LeetCode之Hamming Distance

1、題目

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.      

題意:

給定兩個整數x,y,計算x和y的漢明距離。漢明距離是指x、y的二進制表示中,相同位置上數字不相同的所有情況數。

2、代碼實作

public class Solution {
    public int hammingDistance(int x, int y) {
        int notSame = x ^ y;
        int count = 0;
        while (notSame != 0) {
            if (notSame % 2 == 1)
                ++count;
            notSame /= 2;
        }
        return count;
    }
}      

注意記得用 異或

0 ^ 1 = 1

1 ^ 0 = 1

1 ^ 1 = 0

0 ^ 0 = 0

然後就是我們平時10進制的話,每次去掉末尾的數字是 / 10,二進制的話就是/2,切記。 

繼續閱讀