Skip to content

Leetcode 1356. Sort Integers by The Number of 1 Bits ( Issue #71 ) #78

New issue

Have a question about this project? Sign up for a free account to open an issue and contact its maintainers and the community.

By clicking “Sign up for ”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on ? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
#include<bits/stdc++.h>
using namespace std;

class Solution {
public:

static bool cmp ( int a, int b )
{
int bitsa = 0;
int bitsb = 0;
int ta = a, tb = b;
while( a != 0 )
{
if ( a%2 == 1 )
bitsa++;
a /= 2;
}
while( b != 0 )
{
if ( b%2 == 1 )
bitsb++;
b /= 2;
}
return ( bitsa != bitsb ? bitsa < bitsb : ta < tb);
}

vector<int> sortByBits ( vector<int>& arr ) {
sort( arr.begin(), arr.end(), cmp );
return arr;
}
};