Update 1356.根据数字二进制下1的数目排序.md

增加Java实现
This commit is contained in:
hailincai
2021-09-05 09:44:53 -04:00
committed by GitHub
parent 69441475c6
commit adafd39931

View File

@ -123,6 +123,32 @@ public:
## Java
```java
class Solution {
private int cntInt(int val){
int count = 0;
while(val > 0) {
val = val & (val - 1);
count ++;
}
return count;
}
public int[] sortByBits(int[] arr) {
return Arrays.stream(arr).boxed()
.sorted(new Comparator<Integer>(){
@Override
public int compare(Integer o1, Integer o2) {
// TODO Auto-generated method stub
int cnt1 = cntInt(o1);
int cnt2 = cntInt(o2);
return (cnt1 == cnt2) ? Integer.compare(o1, o2) : Integer.compare(cnt1, cnt2);
}
})
.mapToInt(Integer::intValue)
.toArray();
}
}
```