LC 1356. Sort Integers by The Number of 1 Bits

Nilanjan Deb · April 5, 2020

This is my CPP solution.

class Solution {
private:
    int binCount(int n){
        int cnt = 0;
        while(n){
            n/=2;
            cnt++;
        }
        return cnt;
    }
public:
    vector<int> sortByBits(vector<int>& arr) {
        int n = arr.size();
        sort(arr.begin(),arr.end());
        int l = 0, u = binCount(arr[n-1]);
        vector<int> ans;
        int i = l;
        while(i<=u){
            vector<int> temp;
            int k = 0;
            while(k<n){
                if(bitCount(arr[k]) == i)
                    temp.push_back(arr[k]);
                k++;
            }
            sort(temp.begin(),temp.end());
            int m = 0;
            while(m < temp.size()){
                ans.push_back(temp[m]);
                m++;
            }
            temp.clear();
            i++;
        }
        return ans;
    }
};


Dicussion Forum