力扣1356 根据数字二进制下 1 的数目排序

力扣1356 根据数字二进制下 1 的数目排序

知识点:

  • 十进制转二进制的熟练,关键在于do_while
  • vector的反转方式,reverse函数
  • sort的自定义函数不能是普通成员函数
  • 静态成员函数不能调用非静态函数
class Solution {
public:
    //十进制转二进制
    static vector<int> D2B(const int x){
        vector<int> res;
        int m,n ;        
        int x_cp = x;
        do {                          //使用do while,在判定之前,先写入
            m = x_cp/2;
            n = x_cp%2;
            x_cp = m;
            res.push_back(n);
        }while(x_cp > 0);
        // vector反转的方式

        //方式1
        //reverse(res.begin(),res.end());

        //方式2
        return {res.rbegin(),res.rend()};
    }
    static int countOnes(const vector<int>& B){
        int cnt = 0;
        for(const auto b:B){
            if(b == 1) ++cnt;
        }
        return cnt;
    }

    static bool mycmp(int a, int b){      //必须加static
        //static成员函数不能调用non-static成员函数
        //D2B和countOnes都改为static
        auto Ba = D2B(a);
        auto Bb = D2B(b);
        int aOnes = countOnes(Ba);
        int bOnes = countOnes(Bb);   
        if(aOnes != bOnes) return aOnes < bOnes;
        else return a < b;
    }

    vector<int> sortByBits(vector<int>& arr) {
        auto arr_cp = arr;
        sort(arr_cp.begin(),arr_cp.end(),mycmp);
        return arr_cp;
    }
};

可以记忆一个函数,完美解决这个问题。

官方解法的递推式可以学习一下:

删除最右边的1,值得记忆

public int hammingWeight(int n) {
    int count = 0;
    while (n != 0) {
        n &= n - 1;
        count++;
    }
    return count;
}
原文地址:https://www.cnblogs.com/jinjin-2018/p/13937446.html