两步走:

  • 先异或,得到所有不同位 (r = m^n)
  • 数r有多少位是1即可

c++实现

方法一

class Solution {
public:
    int countBitDiff(int m, int n) {
        int r = m^n, res=0;
        while(r){
            r &= (r-1);
            res++;
        }
        return res;
    }
};

方法二

class Solution {
public:
    int countBitDiff(int m, int n) {
        int r = m^n, res=0;
        unsigned int flag=1;
        while(flag){
            if(flag & r){
                res++;
            }
            flag  = flag << 1;
        }
        return res;
    }
};

python实现

class Solution:
    def countBitDiff(self , m: int, n: int) -> int:
        res=0;
        r = m^n
        while r:
            r &= (r-1)
            res += 1
        return res