Files
leetcode-master/problems/1356.根据数字二进制下1的数目排序.md
youngyangyang04 ab1af02c70 Update
2020-11-06 17:58:47 +08:00

1.6 KiB
Raw Blame History

题目链接

https://leetcode-cn.com/problems/sort-integers-by-the-number-of-1-bits/

思路

这道题其实是考察如何计算一个数的二进制中1的数量。

我提供两种方法:

  • 方法一:

朴实无华挨个计算1的数量最多就是循环n的二进制位数32位。

int bitCount(int n) {
    int count = 0; // 计数器
    while (n > 0) {
        if((n & 1) == 1)  count++;  // 当前位是1count++
        n >>= 1 ; // n向右移位
    }
    return count;
}
  • 方法二

这种方法只循环n的二进制中1的个数次比方法一高效的多

int bitCount(int n) {
    int count = 0;
    while (n) {
        n &= (n - 1); // 清除最低位的1
        count++;
    }
    return count;
}

以计算12的二进制1的数量为例如图所示

下面我就使用方法二,来做这道题目:

C++代码

class Solution {
private:
    static int bitCount(int n) { // 计算n的二进制中1的数量
        int count = 0;
        while(n) {
            n &= (n -1); // 清除最低位的1
            count++;
        }
        return count;
    }
    static bool cmp(int a, int b) {
        int bitA = bitCount(a);
        int bitB = bitCount(b);
        if (bitA == bitB) return a < b; // 如果bit中1数量相同比较数值大小
        return bitA < bitB; // 否则比较bit中1数量大小
    }
public:
    vector<int> sortByBits(vector<int>& arr) {
        sort(arr.begin(), arr.end(), cmp);
        return arr;
    }
};