LeetCode刷题笔记:汉明距离

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.

解题思路

本题需要做的就是把x,y的每一位取出来进行比较,并统计位不等的个数

Solution

class Solution {
public:
    int hammingDistance(int x, int y) {
        int total = 0;
        int n = 32;
        while(n) {
            if((x & 1) != (y & 1)) {
                total += 1;
            }
            x = x >> 1;
            y = y >> 1;   
            n -= 1;
        }
        return total;
    }
};

你可能感兴趣的:(LeetCode刷题笔记,LeetCode刷题笔记)