首页 > 其他 > 详细

【LeetCode】Hamming Distance

时间:2016-12-22 22:52:37      阅读:357      评论:0      收藏:0      [点我收藏+]

问题网址 https://leetcode.com/problems/hamming-distance/

就是一个异或后,求1的位数的问题。

 

看到问题之后,首先困扰是: int能不能求异或?是不是要转成二进制才可以?

答案是肯定的。直接 x^y 就行了。

 

然后就是统计位数的问题了

 

 

答案一:https://discuss.leetcode.com/topic/72636/c-simple-solution-0ms

liupeng的答案

int hammingDistance(int x, int y) {
    
    int tmpInt=x^y;
    int dis=0;
    
    while(tmpInt)
    {
        if((tmpInt>>1)<<1 != tmpInt) 
      //tmpInt右移一位,再左移动一位,相当于最后一位设为0;如果等于原数,就证明原来最后一位就是0.反之,是1
      // 很巧妙 {
++dis; } tmpInt>>=1; } return dis; }

 

后话

如果真的要转成二进制,可以转成字符串

char str[10];
itoa(tmpInt, str, 2);

这个2 可以自由发挥了。别的进制也可以。

【LeetCode】Hamming Distance

原文:http://www.cnblogs.com/xy123001/p/6212941.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!