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;
}
相關文章
相關標籤/搜索