1. 程式人生 > >LeetCode-Hamming Distance

LeetCode-Hamming Distance

Description: 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.

題意:計算給定的兩個整數的Hamming distance;

解法:Hamming distance的定義是兩個數的二進位制表示中,相應位不同的個數(即其中一個當前位為1,另外一個為0);我們只需要將兩個整數進行異或操作,那麼最後可以得到他們之間不同的那個位,即為1的那個位;

class Solution {
    public int hammingDistance(int x, int y) {
        int dif = x ^ y;
        int cnt = 0;
        while (dif > 0) {
            cnt = dif % 2 == 1 ? cnt + 1 : cnt;
            dif /= 2;
        }
        return cnt;
    }
}