461. Hamming Distance

xiaoxiao2021-02-27  179

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. 解题思路:1.C语言中,x & 1 从命令的角度讲,是将x的每一bit(2进制中的1和0都占一个bit)与0001的每一bit做与运算. "&"是"与运算"的意思,1&1=1,其他情况(1&0,0&1,0&0)都=0. 从逻辑的角度来讲,这个命令就是取x的最左边一位.例如x是0011,x&1得到0001,如果x是0110,x&1得到0000. x ^= y是个异或并赋值的操作符。属于位操作符。二者不同返回1,相同返回 0; 意思是 x与y异或的结果存入 x。 假如 x的二进制是 00000000 00000000 00000000 11111111; 或者更长 y的二进制是 00000000 00000000 11111111 00001111; 则 x^=y;之后 x 的二进制是 00000000 00000000 11111111 11110000; x >>= 1 表示将n的二进制表示向右移动一位再赋值给n int hammingDistance(int x, int y) {          int count=0;  while (x || y) { if ((x & 1) ^ (y & 1)) { count++; x >>= 1; y >>= 1;} }             return count;      }  2.Java解法 1 public int hammingDistance(int x, int y) { 2 int xor = x ^ y, count = 0; 3 for (int i=0;i<32;i++) count += (xor >> i) & 1; 4 return count; 5 }
转载请注明原文地址: https://www.6miu.com/read-13088.html

最新回复(0)