public class Solution { public int HammingDistance(int x, int y) { int[] aryA = new int[32]; int[] aryB = new int[32]; int i = 0; int j = 0; do { aryA[i] = x % 2;//将10进制转换为2进制 x = x / 2; i++; } while (x != 0); do { aryB[j] = y % 2;//将10进制转换为2进制 y = y / 2; j++; } while (y != 0); int result = 0; for (int k = 0; k < 32; k++) { if (aryA[k] != aryB[k])//查找对应的二进制位,如果一个是0一个是1 { result++; } } //Console.WriteLine(result); return result; } }
https://leetcode.com/problems/hamming-distance/#/description
将10进制转为2进制
补充一个python的实现,使用位操作:
1 class Solution: 2 def hammingDistance(self, x: int, y: int) -> int: 3 z = x ^ y#求x与y的按位异或(x与y相同则异或为0,x与y不同则异或为1) 4 cnt = 0#存储最终结果 5 mask = 1#定义掩码0000 0000 0000 0000 0000 0000 0000 0001 6 for i in range(31): 7 t = z & mask#掩码与异或结果求按位与,就是计算当前位是否为1 8 if t != 0:#如果按位与等于1,则表示异或值为1,也就是x与y对应为不同 9 cnt += 1#汉明距离+1 10 mask <<= 1#移动掩码位0000 0000 0000 0000 0000 0000 0000 0010 11 return cnt