【LeetCode每日一题】[简单]1356. 根据数字二进制下 1 的数目排序
1356. 根据数字二进制下 1 的数目排序
1356. 根据数字二进制下 1 的数目排序
算法思想:数组
题目:
java代码
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;
}
}