461. Hamming Distance

Problem:

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.

Question: Find the Hamming distance, that is, the number of different digits between two numbers


Idea: Originally, I wanted to shift x and y one bit to the right for each comparison, and judge whether it is 1 after XOR.

The method failed the first time, and after seeing the XOR , I thought of XORing the two numbers first, and then looking at the number of 1 bits in the binary.


Code:

class Solution {
    public int hammingDistance(int x, int y) {
        int ret = 0; 
        int z = x ^ y;
        while(z!=0){
            if((z&1)==1)
                ret++;
            z>>=1;
        }
        return ret;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324775847&siteId=291194637