/**
* Problem: LeetCode 1356 - Sort Integers by The Number of 1 Bits
* Difficulty: Easy
* Language: Java
* Author: CodeByTushu
*/
import java.util.Arrays;
class Solution {
public int[] sortByBits(int[] arr) {
// Since arr[i] <= 10000, we can encode the bit count into the number:
// encoded = bitCount * 10001 + originalValue
for (int i = 0; i < arr.length; i++) {
arr[i] += Integer.bitCount(arr[i]) * 10001;
}
// Sort the primitive array directly in-place
Arrays.sort(arr);
// Decode the original value
for (int i = 0; i < arr.length; i++) {
arr[i] %= 10001;
}
return arr;
}
}
"""
Problem: LeetCode 1356 - Sort Integers by The Number of 1 Bits
Difficulty: Easy
Language: Python
Author: CodeByTushu
"""
from typing import List
class Solution:
def sortByBits(self, arr: List[int]) -> List[int]:
return sorted(arr, key=lambda x: (x.bit_count(), x))
/**
* Problem: LeetCode 1356 - Sort Integers by The Number of 1 Bits
* Difficulty: Easy
* Language: C++
* Author: CodeByTushu
*/
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<int> sortByBits(vector<int>& arr) {
sort(arr.begin(), arr.end(), [](int a, int b) {
int countA = __builtin_popcount(a);
int countB = __builtin_popcount(b);
if (countA != countB) {
return countA < countB;
}
return a < b;
});
return arr;
}
};
/**
* Problem: LeetCode 1356 - Sort Integers by The Number of 1 Bits
* Difficulty: Easy
* Language: JavaScript
* Author: CodeByTushu
*/
/**
* @param {number[]} arr
* @return {number[]}
*/
var sortByBits = function(arr) {
function countBits(n) {
let count = 0;
while (n > 0) {
n &= (n - 1);
count++;
}
return count;
}
return arr.sort((a, b) => {
const bitsA = countBits(a);
const bitsB = countBits(b);
if (bitsA !== bitsB) {
return bitsA - bitsB;
}
return a - b;
});
};