The Hamming distance between two integers is the number of positions at which the corresponding bits are different.spa
Given two integers x
and y
, calculate the Hamming distance.code
Note:
0 ≤ x
, y
< 231.blog
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.
用Java的位运算,
public class Solution { public int hammingDistance(int x, int y) { int sum=0; while(x>0 || y>0) { int x1=x & 1;// 位与:第一个操做数的的第n位于第二个操做数的第n位若是都是1,那么结果的第n为也为1 int y1=y & 1; if((x1^y1)==1)// 第一个操做数的的第n位于第二个操做数的第n位 相反,那么结果的第n为也为1,不然为0 sum++; y=y>>1; // 右移( >> ) 高位补符号位 x=x>>1; } return sum ; } }