1. 程式人生 > >461. Hamming Distance

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.


我的解法

public class Solution {
    public int hammingDistance(int x, int y) {
        int r = x ^ y; //異或;位元位不同返回1
        // 數子轉二進位制字串,轉字元陣列
        char[] cArr = Integer.toBinaryString(r).toCharArray();
        int count = 0;
        for(char c : cArr){
            if(c == '1')
                count ++;
        }
        return count;
    }
}

答案解法

public class Solution {
    public int hammingDistance(int x, int y) {
        int r = x ^ y;
        // 包裝類自帶方法,計算數值中“1”位元的數量
        int count = Integer.bitCount(r);
        return count;
    }
}