Sort Integers by The Number of 1 Bits
给一组数,按照里面二进制1的个数排序.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class Solution { public int[] sortByBits(int[] arr) { return Arrays.stream(arr).boxed().sorted((a,b) -> (countBit(a) == countBit(b)) ? a-b : countBit(a) - countBit(b)).mapToInt(i -> i).toArray(); } private int countBit(int n) { int res = 0; for(int i = 0 ; i < 32; i++) { if((n & (1 << i)) != 0) res++; } return res; } } |