1. 程式人生 > >leetcode_461. Hamming Distance 計算漢明距離,按位異或運算,計算整數的二進位制表示中1的個數 java

leetcode_461. Hamming Distance 計算漢明距離,按位異或運算,計算整數的二進位制表示中1的個數 java

題目:

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 ≤ xy < 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的二進位制表示中,相同位置上數字不相同的所有情況數。

程式碼:

public class Solution {
    public int hammingDistance(int x, int y) {
        int z = x^y;              #先將x,y按位異或運算,得到不相同位置上為1的整數z
        int res = 0;
        while(z != 0) {            #計算整數z的二進位制中1的個數,即為x和y的漢明距離
            if (z%2 == 1) {
                res++;
            }
            z = z/2;
        }
        return res;
    }
}

筆記:

最近都會用java寫程式碼哦。