【LeetCode】461 Hamming Distance

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, calculate the Hamming distance.

Note:
0 ≤  x y  < 2 31 .


解题思路:汉明距离就是两个数的位数不同的个数。输入x和y先将x和y转化为二进制表示,用两个长度为32的整数数组存储,然后逐一比较两个数组的不同的位数。


代码如下:

public class Solution {
    public int hammingDistance(int x, int y) {
        int a[] = new int[33];
        int b[] = new int[33];
        int i = 0;
        int j = 0;
        int num = 0;
        while(x>0)
        {
            a[i++] = x%2;
            x /=2;
        }
        while(y>0)
        {
            b[j++] = y%2;
            y /=2;
        }
        
        for(i =0;i<33;i++)
        {
            if(a[i] != b[i])
                num++;
        }
        return num;
    }
}

你可能感兴趣的:(leetcode刷题)