1356. Sort Integers by The Number of 1 Bits

class Solution {
public int[] sortByBits(int[] arr) {
Integer[] arrObject = new Integer[arr.length];
for (int i = 0; i < arr.length; i++) {
arrObject[i] = arr[i];
}
Arrays.sort(arrObject, new Comparator() {
@Override
public int compare(Integer o1, Integer o2) {
if (countOnes(o1) == countOnes(o2))
return o1.compareTo(o2);
else if (countOnes(o1) > countOnes(o2))
return 1;
else
return -1;
}
});
for (int i = 0; i < arr.length; i++) {
arr[i] = arrObject[i];
}
return arr;
}
public static int countOnes(int n) {
int count = 0;
while (n != 0) {
n = n & (n - 1);
count++;
}
return count;
}
}

### Like this:

Like Loading...

*Related*