LeetCode-461. Hamming Distance

Posted 码上哈希

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode-461. Hamming Distance相关的知识,希望对你有一定的参考价值。

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.

思路:算两个数二进制按位比较不同位的个数,先异或,再求xor的二进制1的个数。

public class Solution {
    public int hammingDistance(int x, int y) {
        int xor = x ^ y;
        int distance = 0;
        while (xor != 0) {
            distance ++;
            xor &= (xor-1); //清除xor最右边的1
        }
        return distance;
    }
}

 

以上是关于LeetCode-461. Hamming Distance的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode(461) Hamming Distance

LeetCode(461) Hamming Distance

LeetCode 461. Hamming Distance

LeetCode-461. Hamming Distance

leetcode 461. Hamming Distance

leetcode461 - Hamming Distance - easy