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.
答案描述上来说,就是找出两个数的异或位的个数。
leetcode上有个别人写的一行代码,就是直接借助了Integer库的方法,当然我是想不到的啦。
public class Solution {
public int hammingDistance(int x, int y) {
return Integer.bitCount(x ^ y);
}
}
自己写的算法在下面,就是进行位操作。
每次比较最后一位,然后对两组数进行右移操作,直到最大的那个数等于0为止。
public class Solution {
public int hammingDistance(int x, int y) {
int hamDistance = 0;
while((x>0)||(y>0)){
if((x&1)!=(y&1)){
hamDistance++;
}
x=x>>>1;
y=y>>>1;
}
return hamDistance;
}
}