461 Hamming distance

Title Description

Hamming distance between two integers refers to two figures corresponding to the number of different bit positions.

Given two integers x and y, the calculation of the Hamming distance between them.

Note:
0 ≤ X, Y <2 ^ 31 is.

Example:

Input: x = 1, y = 4

Output: 2

Ideas analysis

Two ideas

  • A thinking: calculate two different number of bits is the Hamming distance. And 1 and each bit is calculated by, for unsigned right shift.
  • Thinking two: the number two XOR, the rest is different from a median of 1, 1-digit calculated distance is the Hamming distance.

Code

    /**
     * 每次无符号右移,找到不同的位的个数就是汉明距离
     * @param x
     * @param y
     * @return
     */
    public static int hammingDistance(int x, int y) {
        int count = 0;
        while (x != 0 && y != 0) {
            if ((x & 1) != (y & 1)) {
                count++;
            }
            x >>>= 1;
            y >>>= 1;
        }
        while (x != 0) {
            count = (x & 1) == 1 ? count + 1 : count;
            x >>>= 1;
        }
        while (y != 0) {
            count = (y & 1) == 1 ? count + 1 : count;
            y >>>= 1;
        }
        return count;
    }

    /**
     * 两数异或,剩下的就是不同的位为1
     * n & n-1,会将n最右的1位变成0
     * 从而计算两者距离
     * @param x
     * @param y
     * @return
     */
    public static int hammingDistance1(int x, int y) {
        int tmp = x ^ y;
        int count = 0;
        while (tmp != 0) {
            count++;
            tmp &= (tmp - 1);
        }
        return count;
    }

Published 117 original articles · won praise 8 · views 3689

Guess you like

Origin blog.csdn.net/qq_34761012/article/details/104608178