LeetCode题解:Hamming Distance

来源:互联网 发布:计算json长度工具 编辑:程序博客网 时间:2024/06/05 20:52

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.

思路:

先通过异或得到不同的位,然后计数。

题解:

int hammingDistance(int x, int y) {    int v = x ^ y;    int nbits(0);    while(v) {        if (v & 1) {            ++nbits;        }        v >>= 1;    }    return nbits;}


0 0