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 ; } }