Hamming距离

版权声明:世界是开源的 https://blog.csdn.net/qq_36619282/article/details/81983580

两个整数的Hamming距离是对应比特位不同的个数。
给定两个整数x和y,计算两者的Hamming距离

样例
输入: x = 1, y = 4

输出: 2

public class Solution {
    public int hammingDistance(int x, int y) {
        int Distance=0;

        while ( x != 0 || y != 0 ) {
            if ( x % 2 != y % 2 ) {
                Distance ++;
            }
            x /= 2;
            y /= 2;
        }
        return Distance;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_36619282/article/details/81983580