diff --git a/problems/1356.根据数字二进制下1的数目排序.md b/problems/1356.根据数字二进制下1的数目排序.md index 660434a2..40a49b9c 100644 --- a/problems/1356.根据数字二进制下1的数目排序.md +++ b/problems/1356.根据数字二进制下1的数目排序.md @@ -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(){ + @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(); + } +} ```