461. Hamming Distance

Question:

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.

Example 1:

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.

 

Note:  0 ≤ xy < 2^31.

Solution:

class Solution {
public:
    int hammingDistance(int x, int y) {
        int z = x xor y;
        int sum = 0;
        int judge;
        for(int i = 0; i < 32; i ++) {
            judge = 1 << i;
            if (judge & z) {
                sum = sum + 1;
            }
        }
        return sum;
    }
};

题目直达:https://leetcode.com/problems/hamming-distance/#/description

posted @ 2017-04-24 19:38  SapphireCastle  阅读(97)  评论(0编辑  收藏  举报