leetcode算法题1: 两个二进制数有多少位不相同?异或、位移、与运算的主场

/*
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.c++

Given two integers x and y, calculate the Hamming distance.spa

Note:
0 ≤ x, y < 231.code

Example:rem

Input: x = 1, y = 4it

Output: 2io

Explanation:class

1 (0 0 0 1)二进制

4 (0 1 0 0)gc

The above arrows point to positions where the corresponding bits are different.
*/
int hammingDistance(int x, int y) {im

}

题意: 输入两个int,求这两个数的二进制数的不一样的位的个数。

办法一:

* 能够利用异或的特性:相同为0,不一样为1。把两数异或,再判断结果有几个1。

  * 怎么判断int中有几个1?

    * 能够对这个数除2运算,并记录模2为1的个数,直至此数变到0。也就是模拟了转二进制数的过程。

办法二:

* 先异或。

* 如何判断有几个1?

  * 右移一位,再左移一位,若是不等于原数,就是有一个1。一样模拟了转二进制数的过程。

  * 除2即右移一位。

办法三:

* 先异或。

* 如何判断有几个1?

while(n) {
    c++;
    n=n&(n-1);
}

n&(n-1)就是把n的最未的1变成0。


#include <stdio.h>

int hammingDistance(int x, int y) {
    int r = x ^ y;
    int cnt = 0;
    while (r > 0) {
        if (r%2 == 1) {
            cnt ++;
        }
        r = r/2;
    }
    return cnt;
}

int hammingDistance2(int x, int y) {
    int r=x^y;
    int cnt = 0;
    while (r) {
        if ((r>>1)<<1 != r) {
            cnt ++;
        }    
        r >>= 1;
    }
    return cnt;
}

int hammingDistance3(int x, int y) {
    int r=x^y;
    int cnt=0;
    while (r) {
        cnt ++;
        r=r&(r-1);
    }
    return cnt;
}

int main(int argc, char *argv[])
{
    printf("%d\n", hammingDistance3(1,4));
    return 0;
}
相关文章
相关标签/搜索