diff --git a/Algorithms/Easy/1356_SortIntegersbyTheNumberof1Bits/1356_Sort Integers by The Number of 1 Bits.cpp b/Algorithms/Easy/1356_SortIntegersbyTheNumberof1Bits/1356_Sort Integers by The Number of 1 Bits.cpp new file mode 100644 index 0000000..e488d28 --- /dev/null +++ b/Algorithms/Easy/1356_SortIntegersbyTheNumberof1Bits/1356_Sort Integers by The Number of 1 Bits.cpp @@ -0,0 +1,31 @@ +#include +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 sortByBits ( vector& arr ) { + sort( arr.begin(), arr.end(), cmp ); + return arr; + } +};