Given an array of non-negative integers, count the number of unordered pairs of array
elements such that their bitwise AND is a power of 2.
For example, let’s say the array is arr = [10, 7, 2, 8, 3], and let ‘&’ denote the bitwise AND
operator. There are 6 unordered pairs of its elements that have a bitwise AND that is a
power of two:
For indices (0,1), 10 & 7 = 2, which is a power of 2.
For indices (0,2), 10 & 2 = 2, which is a power of 2.
For indices (0,3), 10 & 8 = 8, which is a power of 2.
For indices (0,4), 10 & 3 = 2, which is a power of 2.
For indices (1,2), 7 & 2 = 2, which is a power of 2.
For indices (2,4), 2 & 3 = 2, which is a power of 2.
Therefore, the answer is 6.
public static long countPairs(List<Integer> arr) {
// Write your code here
int count = 0;
for(int i = 0; i < arr.size(); i++){
for(int j= i+1; j < arr.size(); j++){
double a = Math.log(arr.get(i).intValue()&arr.get(j).intValue())/Math.log(2) ;
if(a == (int) a)
count++;
}
}
return count;
}