【LeetCode】Hamming Distance

问题网址 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 可以自由发挥了。别的进制也可以。

原文地址:https://www.cnblogs.com/xy123001/p/6212941.html