欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

461. Hamming Distance【数学|位运算】

发布时间:2023/12/10 编程问答 35 豆豆
生活随笔 收集整理的这篇文章主要介绍了 461. Hamming Distance【数学|位运算】 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

2017/3/14 15:23:55


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.

 

题目要求:求两个数字二进制位中同一位置不同bit的个数。

解法1  Java    利用1的移位依次匹配是否对应位为1,统计为1的个数。

 

public class Solution {public int hammingDistance(int x, int y) {x ^= y;int count = 0;for ( int i=0;i<32;i++ )count = (1<<i & x ) !=0 ? count+1 : count;return count;} }

解法2 Java   利用 a &= a-1 依次去掉最后一个1,统计循环次数。

public class Solution {public int hammingDistance(int x, int y) {x ^= y;int count = 0;while( x != 0 ){x &= x - 1;count++;}return count;} }

  

转载于:https://www.cnblogs.com/flyfatty/p/6624801.html

总结

以上是生活随笔为你收集整理的461. Hamming Distance【数学|位运算】的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。