Solution
The correct answer is option 2.
Concept:
The given c function is,
int f(unsigned int N)
{
unsigned int counter = 0;
while (N > 0)
{
counter += N & 1;
N = N >> 1;
}
return counter == 1;
}
Explanation:
When N=1:
If the function N=1 then,
counter=0,
Iteration 1:
The while-loops enters and the expression counter += N & 1;
counter = 0+1 & 1;
counter =1
The expression is N = 1 >> 1;
N=0
>> is right shift operator so N become 0 and the next iteration the condition becomes false.
The while loop will execute and it returns 1 as output.
Here 1==1 is true hence it prints the 1 as output.
When N=2:
If the function N=2 then,
counter=0,
iteration 1:
The while-loops enters and the expression counter += N & 1;
counter = 0+2 & 1;
counter =0+0
counter =0
The expression is N = 2 >> 1;
N=1
>> is right shift operator so N become 1 and the next iteration the condition becomes true.
Iteration 2:
The while-loops enters and the expression counter += N & 1;
counter = 0+1 & 1;
counter =0+1
counter =1
The expression is N = 1 >> 1;
N=0
>> is right shift operator so N become 0 and the next iteration the condition becomes false.
counter == 1;
Here 1==1 is true hence it prints the 1 as output.
The while loop will execute and it returns 1 as output.
When N=3:
If the function N=3 then,
counter=0,
Iteration 1:
The while-loops enters and the expression counter += N & 1;
counter = 0+3& 1;
counter =0+1
counter =1
The expression is N = 3 >> 1;
N=1
>> is right shift operator so N become 1 and the next iteration the condition becomes true.
teration 2:
The while-loops enters and the expression counter += N & 1;
counter = 1+1 & 1;
counter =1+1
counter =2
The expression is N = 1 >> 1;
N=0
>> is the right shift operator so N becomes 0 and the next iteration the condition becomes false.
The while loop will execute and it returns 0 as output.
Here 2==1 is False hence it prints the 0 as output.
When N=4 then it prints the 1 as output.
When N=5 then it prints the 0 as output.
When N=6 then it prints the 0 as output.
When N=7 then it prints the 0 as output.
When N=8 then it prints the 1 as output.
Hence the correct answer is 1 if N is a power of 2, otherwise 0.