【发布时间】:2022-02-09 11:58:52
【问题描述】:
我在 geeksforgeeks 中解决问题时突然明白了这一点。我了解“Integer.compare”的使用,但无法在 sortBySetBitCount 方法中使用“->”。
static void sortBySetBitCount(Integer arr[], int n)
{
Arrays.sort(arr, (a, b) -> Integer.compare(countSetBit(b), countSetBit(a)));
//I mean here the "->" operator
}
static int countSetBit(int n) {
int count = 0;
while (n>0) {
n = n & (n - 1);
count += 1;
}
return count;
}
【问题讨论】:
-
顺便说一句,你可以使用
countSetBit方法而不是Integer.bitCount -
在 Oracle 跟踪网站上了解 Lambda expressions in Java。
-
在 countSetBit 方法中应该是 while(n != 0)。
标签: java