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;
}
}
Leetcode 461. Hamming Distance
最新推荐文章于 2023-12-18 09:47:53 发布