首页 > 代码库 > Leetcode 461. Hamming Distance JAVA语言

Leetcode 461. Hamming Distance JAVA语言

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.

PS:求海明距离。

思路:就是求x和y二进制的异或中的1的个数

public class Solution {
    public int hammingDistance(int x, int y) {
        // String x1=Integer.toBinaryString(x);
        // String y1=Integer.toBinaryString(y);
        int tem=x^y;
        int count=0;
        String str=Integer.toBinaryString(tem);
        for(int i=0;i<str.length();i++){
            if(str.charAt(i)==‘1‘){
                count++;
            }
        }
        // System.out.println(count);
        
        return count;
    }
}


Leetcode 461. Hamming Distance JAVA语言