p39 求汉明距离 (leetcode 461)

一:解题思路

这个题目的解法为:先将2个数进行异或,然后求出异或结果中有多少个1即可。

二:完整代码示例 (C++版和Java版)

C++:

class Solution 
{
public:
    int numberofOne(int x)
    {
        int count = 0;

        while (x != 0)
        {
            count++;

            x &= (x-1);
        }

        return count;
    }

    int hammingDistance(int x, int y) 
    {
        return numberofOne(x^y);
    }
};

Java:

class Solution 
{
    public int numberofOne(int x)
    {
        int count=0;
        
        while(x!=0)
        {
            count++;
            
            x&=(x-1);
        }
        
        return count;
    }
    
    public int hammingDistance(int x, int y) 
    {
        return numberofOne(x^y);
    }
}

 

posted @ 2020-03-15 17:42  repinkply  阅读(104)  评论(0)    收藏  举报