leetcode461

    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
 4         cnt = 0
 5         mask = 1
 6         for i in range(31):
 7             t = z & mask
 8             mask <<= 1
 9             if t != 0:
10                 cnt += 1
11         return cnt
原文地址:https://www.cnblogs.com/asenyang/p/6732154.html