Leetcode题解-461. Hamming Distance

Leetcode题解-461. Hamming Distance【easy】

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 < 2^31.

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.

思路

汉明距离(Hamming Distance)指的是两个等长的二进制串对应位置不同字符的个数。第一种方法,将两个十进制整数转换为二进制数,然后从最低位开始逐位相比(感觉比较麻烦);第二种方法将两个十进制数进行异或操作等到result,然后模拟手算将result转换为二进制数,result的二进制表示有几个1就代表汉明距离是几(这里采用这种方法)。

代码

int hammingDistance(int x, int y) {
        int count = 0, result = x ^ y;
        while(result != 0){
            if(result % 2 == 1) count++;
            result /= 2;
        }
        return count;
    }

你可能感兴趣的:(Leetcode)