Hamming Distance

https://leetcode.com/problems/hamming-distance/description/

TheHamming distancebetween two integers is the number of positions at which the corresponding bits are different.

Given two integersxandy, calculate the Hamming distance.

Thoughts

找不同bit想到XOR. 然后再数XOR后有多少个1. 通过把32位不断右移后与1相与.

Code

class Solution {
    public int hammingDistance(int x, int y) {
        int xor = x ^ y, count = 0;
        for (int i = 0; i < 32; i++) {
            count += (xor >> i) & 1;
        }
        return count;
    }
}

Analysis

时间复杂度O(1).

Last updated