码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-07-15 19:48:50      阅读:273      评论:0      收藏:0      [点我收藏+]

标签:which   ber   integer   comm   pos   pretty   ble   point   分享   

/* 
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.

Note: 
0 ≤ x, y < 231.

Example:

Input: x = 1, y = 4

Output: 2

Explanation:

1 (0 0 0 1)

4 (0 1 0 0)

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

}

题意: 输入两个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;
}

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

标签:which   ber   integer   comm   pos   pretty   ble   point   分享   

原文地址:http://www.cnblogs.com/freeself/p/7183761.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!