C++零基础100题-位运算综合

261 阅读1分钟

题目链接: leetcode.cn/problems/ha…

题目描述

image.png

解题思路

  1. 首先我们要计算两个数字之间有多少位二进制是不同的。我们就要对两个位进行异或运算
  2. 异或运算结果放入get1Cnt函数里面去。
  3. 然后通过这个函数计算我们传递进来的数字里面有多少个1
  4. 返回结果

代码实现

class Solution {
    int get1Cnt(int x){
        int cnt=0;
        while(x>0){
            x &=(x-1);
            cnt++;
        }
        return cnt;
    }
public:
    int hammingDistance(int x, int y) {
        return get1Cnt(x^y);
    }
};