您的位置:首页 > 其它

Leetcode 461. Hamming Distance

2017-03-18 04:54 344 查看
public class Solution {
private final int LENGTH = 32;
public int hammingDistance(int x, int y) {
int[] bits_x = new int[LENGTH];
int[] bits_y = new int[LENGTH];

// calculate binary codes for x and y
int k = 0;
while (x > 0) {
bits_x[k++] = x%2;
x /= 2;
}
k = 0;
while (y > 0) {
bits_y[k++] = y%2;
y /= 2;
}

// count the distance
int distance = 0;
for (int i=0; i<LENGTH; i++) {
if (bits_x[i] != bits_y[i])
distance++;
}

return distance;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: