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); } }

浙公网安备 33010602011771号