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.

Note:
0 ≤ xy < 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) 

说明:

给定两个32位的有符号型整数,当每一位不相同时,加上1,输出最后一共有多少位不相同。

代码如下:

    int hammingDistance(int x, int y) 
    {
        int xx,yy,count=0;
        for(int i=0;i<32;i++)
        {
            xx=x&1;
            yy=y&1;
            if(xx!=yy)
                count++;
            x>>=1;
            y>>=1;
        }
        return count;
    }

代码浅显易懂,实测6ms,beats 72.58% of cpp submissions。

这道题在评论区还看到了令人耳目一新的做法,采用异或,当两位相同时输出0,当两位不同时输出1。不过这种做法的时间花费实际还是跟上述代码差不多的。

代码如下:

    int hammingDistance(int x, int y) 
    {
        int result=x^y,t1,count=0;
        for(int i=0;i<32;i++)
        {
            t1=result&1;
            if(t1==1)
                count++;
            result>>=1;
        }
        return count;
    }

猜你喜欢

转载自www.cnblogs.com/king-3/p/8948404.html