码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-03-27 00:27:00      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:ref   integer   class   font   space   amp   org   wiki   pac   

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的个数。

 

  1. publicclassSolution{
  2. publicint hammingDistance(int x,int y){
  3. x ^= y;
  4. int count =0;
  5. for(int i=0;i<32;i++)
  6. count =(1<<i & x )!=0? count+1: count;
  7. return count;
  8. }
  9. }
 

 

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

  1. publicclassSolution{
  2. publicint hammingDistance(int x,int y){
  3. x ^= y;
  4. int count =0;
  5. while( x !=0){
  6. x &= x -1;
  7. count++;
  8. }
  9. return count;
  10. }
  11. }
 

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

标签:ref   integer   class   font   space   amp   org   wiki   pac   

原文地址:http://www.cnblogs.com/flyfatty/p/6624801.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!