Count Pairs With XOR in a Range LeetCode solution in Python
1class Solution:2def countPairs(self, nums, low, high):3return self._countPairs(nums, high + 1) - self._countPairs(nums, low)45def _countPairs(self, nums, high):6res = 07for k in range(31, -1, -1):8target = high >> k9if target & 1 == 0:10continue11target -= 112counter = Counter(num >> k for num in nums)13for mask in counter:14res += counter[mask] * counter[target ^ mask]15if mask == target ^ mask:16res -= counter[mask]17return res // 2