retagged by
556 views
2 votes
2 votes
int a[20];
unsigned int m; // global variable 
int foo(int a[]) {
	int i=0,count = 0;
	while(i < 20) m |= 1<<(a[i++]-1);
	i = (sizeof(int)<<3)-1;
	while(i>=0) 
		if(m&(1<<(i--))) count++;
	return count;
}

In the above C code,

Array a is initialized with elements $1\leq a[i] \leq 30$ and passed to this function, output of the function foo() is,

(Assume size of int is $4$ bytes)

A No of distinct elements in a[] which are more than $20$

B No of distinct elements in a[] which less than $20$

C No of distinct elements in a[]

D None of these 

retagged by

1 Answer

Best answer
3 votes
3 votes
int a[20];
unsigned int m; // global variable 
int foo(int a[]) {
	int i=0,count = 0;
	while(i < 20) 
	{
	    m |= 1<<(a[i++]-1);
//biwise OR, if a[i] is x, xth bit in m becomes 1
	}
	i = (sizeof(int)<<3)-1;
//i = 4 << 3 - 1, i = 31
//i should have been 30 for below code
	while(i>=0) 
		if(m&(1<<(i--))) count++;
//count gets incremented for each bit of m == 1
	return count;
//Returns the no. of distinct elements in a (a can have only 20 elements)
}
selected by
Answer:

Related questions