[LeetCode one question per day] [Simple] 1356. Sort according to the number of 1 under the digital binary
1356. Sort according to the number of 1s in digital binary
1356. Sort according to the number of 1 in digital binary.
Algorithm idea: Array
topic:
java code
class Solution {
public int[] sortByBits(int[] arr) {
for (int i = 0; i < arr.length; i++) {
arr[i] += Integer.bitCount(arr[i]) * 100000;//1的个数最多16位,两位数,所以使用100000来保存
//使用nteger.bitCount(arr[i])来获取数二进制1的个数效率高,使用的是位运算
}
Arrays.sort(arr);//排序
for (int i = 0; i < arr.length; i++) {
arr[i] = arr[i] % 100000;//还原
}
return arr;
}
}