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
题目这么简单,一行代码就搞定了:
public class HammingDistance461 {
public int hammingDistance(int x, int y) {
return Integer.bitCount(x ^ y);
}
}
本文介绍了一种简单的方法来计算两个整数之间的汉明距离。汉明距离是指两个整数对应的二进制位中不同的位置数量。通过使用Java内置的Integer.bitCount()方法和异或运算符,可以快速准确地计算出结果。
1154

被折叠的 条评论
为什么被折叠?



