For number and , we can found that ones in plus ones in , equals to the ones in plus ones in .
E.g. for and , their binary formats are and ,
(3 & 2).bit_count() equals to 1,
(3 | 2).bit_count() equals to 2.
Thus, for this problem, we need to find any pair of numbers where the
sum of their bit_count() is greater or equal than . We can use a binary search algorithm
to achieve this.
class Solution: def countExcellentPairs(self, nums: List[int], k: int) -> int: res = 0 nums = set(nums)
def bitcount(x: int): c = 0 while x: c += x & 1 x >>= 1 return c
length = len(nums) binl = sorted([bitcount(i) for i in nums]) for ii, i in enumerate(binl): pos = bisect.bisect_left(binl, k - i) t = length - pos res += t return res