Company: Google
Question:
Question:
Write a program to find the sum of bit differences in all pairs that can be formed from array elements n. Bit difference of a pair (x, y) is a count of different bits at same positions in binary representations of x and y. For example, bit difference for 2 and 7 is 2. Binary representation of 2 is 010 and 7 is 111 ( first and last bits differ in two numbers).
Input: The first line of input contains an integer T denoting the number of test cases. First line of the test case will contain an array of elements n.
Output: The sum of bit differences of all pairs that can be formed by given array.
Constraints:
Output: The sum of bit differences of all pairs that can be formed by given array.
Constraints:
1 <=T<= 100
1 <=N<= 10
1 <=a[i]<= 10
Example:
Example:
Input:
2
2
1 2
3
1 3 5
2
1 2
3
1 3 5
Output:
4
8
CODE:
import java.util.*;
import java.lang.*;
import java.io.*;
class Solution
{
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
sc.nextLine();
while(t-->0){
int n = sc.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
int c=0;
for(int i=0;i<n-1;i++){
for(int j=i+1;j<n;j++){
c+=sum(a[i],a[j]);
}
}
System.out.println(2*c);
}
}
static int sum(int n, int m){
int q=m^n;
int c=0;
while(q>0){
c+=q%2;
q/=2;
}
return c;
}
}
Execution Time:0.12
Comments
Post a Comment