public class Solution
{
public int HammingDistance(int x, int y)
{
int[] aryA = new int[];
int[] aryB = new int[]; int i = ;
int j = ; do
{
aryA[i] = x % ;//将10进制转换为2进制
x = x / ;
i++;
}
while (x != ); do
{
aryB[j] = y % ;//将10进制转换为2进制
y = y / ;
j++;
}
while (y != ); int result = ;
for (int k = ; k < ; k++)
{
if (aryA[k] != aryB[k])//查找对应的二进制位,如果一个是0一个是1
{
result++;
}
}
//Console.WriteLine(result);
return result;
}
}

https://leetcode.com/problems/hamming-distance/#/description

将10进制转为2进制

补充一个python的实现,使用位操作:

 class Solution:
def hammingDistance(self, x: int, y: int) -> int:
z = x ^ y
cnt =
mask =
for i in range():
t = z & mask
mask <<=
if t != :
cnt +=
return cnt
05-02 23:10