461 LeetCode 汉明距离

题目描述:
461 LeetCode 汉明距离_第1张图片
思路:方法一:根据题目的理解,找出不一样的位置,因为都是0,1,所以使用异或操作,把两个数异或,再统计该数二进制里面的1的个数;
方法二:

代码如下:一个笨方法:依次比较每个二进制数,统计不同的位置的个数;

class Solution {
public:
    int hammingDistance(int x, int y) {
    return bitset<32>(x^y).count();
    }
};
class Solution {
public:
    int hammingDistance(int x, int y) {
        int num=0;
    while(x!=0&&y!=0){
        if(x%2!=y%2){
          x/=2;
          y/=2;
          num++;}
        else {
        x/=2;
        y/=2;}
    }
    while(x==0&&y!=0){
        if(y%2==1){
        num++;
        y/=2;}
        else{
            y/=2;
        }
    }
    while(y==0&&x!=0){
        if(x%2==1){
        num++;
        x/=2;}
        else{
            x/=2;
        }
    }
    return num;
    }
};

你可能感兴趣的:(leetcode,LeetCode,C++,计算机,代码,编程)