LeetCode 461. 汉明距离
Posted 数据结构和算法
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 461. 汉明距离相关的知识,希望对你有一定的参考价值。
想看更多算法题,可以扫描上方二维码关注我微信公众号“数据结构和算法”,截止到目前我已经在公众号中更新了500多道算法题,其中部分已经整理成了pdf文档,截止到目前总共有1000多页(并且还会不断的增加),可以在公众号中回复关键字“pdf”即可下载。
public int hammingDistance(int x, int y) {
return Integer.bitCount(x ^ y);
}
一行代码搞定,这题实际上没什么难度,我们只需要计算x和y的异或结果,然后再计算这个结果的二进制中1的个数即可。在之前我们分3个系列分别讲到了二进制中1的个数
364,位1的个数系列(一)
385,位1的个数系列(二)
402,位1的个数系列(三)
当然这题答案非常多,下面我们再来看两种写法
public int hammingDistance(int x, int y) {
int xor = x ^ y;
int res = 0;
while (xor != 0) {
res += xor & 1;
xor = xor >>> 1;
}
return res;
}
或者
public int hammingDistance(int x, int y) {
int xor = x ^ y;
int res = 0;
while (xor != 0) {
res += 1;
xor &= xor - 1;
}
return res;
}
以上是关于LeetCode 461. 汉明距离的主要内容,如果未能解决你的问题,请参考以下文章