Leetcode Hamming Distance

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 < 231.

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.

class Solution {
    public int hammingDistance(int x, int y) {
        int xor = x ^ y, count = 0;
        for (int i=0;i<32;i++) count += (xor >> i) & 1;
        return count;
    }
}

 涉及到位运算。

java位运算:Java提供的位运算符有:左移( << )、右移( >> ) 、无符号右移( >>> ) 、位与( & ) 、位或( | )、位非( ~ )、位异或( ^ ),除了位非( ~ )是一元操作符外,其它的都是二元操作符。

1. m<<n的含义:把整数m表示的二进制数左移n位,高位移出n位都舍弃,低位补0.  (此时将会出现正数变成负数的可能)

    m<<n即在数字没有溢出的前提下,对于正数和负数,左移n位都相当于m乘以2的n次方.

2. m>>n的含义:把整数m表示的二进制数右移n位,m为正数,高位全部补0;m为负数,高位全部补1。

 m>>n即相当于m除以2的n次方,得到的为整数时,即为结果。如果结果为小数,此时会出现两种情况:

    如果m为正数,得到的商会无条件 的舍弃小数位;如果m为负数,舍弃小数部分,然后把整数部分加+1得到位移后的值。

3. m>>>n:整数m表示的二进制右移n位,不论正负数,高位都补0。

4. ~ 按位取反操作符,对每个二进制位的内容求反,即1变成0,0变成1。

5. & 位与操作符,对应的二进制位进行与操作,两个都为1才为1,其他情况均为0

6.  | 位或操作符,对应的二进制位进行或操作,两个都为0才为0,其他情况均为1。

7. ^ 异或操作符,相同位值为0 否则为1

posted @ 2017-10-22 16:54  -zzmher  阅读(122)  评论(0编辑  收藏  举报