Leetcode461 Hamming Distance

Hamming distance is an interesting metric that is widely applied in several domains, e.g. in coding theory for error detection, in information theory for quantifying the difference between strings.
but what is Humming Distance? it is the number of different bits of two binary number.

idea1: input two numbers, XOR them, count the number of 1s in the results.
if you knew we have a built in function that can count the number of 1s in a binary number. which make this problem easy as hell.

class Solution {
    public int hammingDistance(int x, int y) {
        return Integer.bitCount(x ^ y); 
    }
}

idea2:
but idea 1 is not really what we want,
so this problem can be divided into two parts:

  1. XOR
  2. count bits
class Solution {
    public int hammingDistance(int x, int y) {
        int r = x ^ y;
        int res = 0;
        while (r != 0) {
            if (r % 2 == 1) {
                res++;
            }
            r = r >> 1;
        }
        return res;
    }
}

idea3:
in idea2, we count the number of 1s by moving one step each time. this might be a bit of slow, and do we have another time to get the rightmost 1 the fastest way?
the answer is yes:
using x&(x-1) will eliminate the rightmost 1. so each time a 1 is eliminated and still not equals to 0 means that we have A 1 in the res.

class Solution {
    public int hammingDistance(int x, int y) {
        int r = x ^ y;
        int res = 0;
        while (r != 0) {
            res++;
            r = r & (r - 1);
        }
        return res;
    }
}
posted @ 2020-08-01 05:42  EvanMeetTheWorld  阅读(21)  评论(0)    收藏  举报