题目
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;
}
}