1.题目要求:
两个整数之间的 汉明距离 指的是这两个数字对应二进制位不同的位置的数目。
给你两个整数 x 和 y,计算并返回它们之间的汉明距离。
示例 1:
输入:x = 1, y = 4
输出:2
解释:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
上面的箭头指出了对应二进制位不同的位置。
示例 2:
输入:x = 3, y = 1
输出:1
提示:
0 <= x, y <= 231 - 1
2.题目代码:
int hammingDistance(int x, int y) {
int x_1 = x;
int count_x = 0;//求出x的二进制位的个数
while(x_1){
count_x++;
x_1 /= 2;
}
int y_1 = y;//求出y的二进制位的个数
int count_y = 0;
while(y_1){
count_y++;
y_1 /= 2;
}
//判断那个个数多
if(count_x > count_y){
int* number_x = (int*)malloc(sizeof(int) * count_x);//求出的x的二进制数组
int* number_y = (int*)malloc(sizeof(int) * count_x);//求出的y的二进制数组
int j_x = count_x - 1;
int j_y = count_x - 1;
//把x,y的二进制都存入数组中
while(j_x >= 0){
number_x[j_x] = x % 2;
j_x--;
x /= 2;
}
while(j_y >= 0){
number_y[j_y] = y % 2;
j_y--;
y /= 2;
}
int diff = 0;//设置变量,找不同
for(int i = 0;i < count_x;i++){
if(number_x[i] != number_y[i]){
diff++;
}
}
return diff;
}else{
int* number_x = (int*)malloc(sizeof(int) * count_y);//求出的x的二进制数组
int* number_y = (int*)malloc(sizeof(int) * count_y);//求出的y的二进制数组
int j_x = count_y - 1;
int j_y = count_y - 1;
//把x,y的二进制都存入数组中
while(j_x >= 0){
number_x[j_x] = x % 2;
j_x--;
x /= 2;
}
while(j_y >= 0){
number_y[j_y] = y % 2;
j_y--;
y /= 2;
}
int diff = 0;//设置变量,找不同
for(int i = 0;i < count_y;i++){
if(number_x[i] != number_y[i]){
diff++;
}
}
return diff;
}
}