What does the following function f() in 'C' return? int f(unsigned int N) {…
2021
What does the following function f() in 'C' return?
int f(unsigned int N) {
unsigned int counter = 0;
while(N > 0) {
counter += N & 1; N = N >> 1;
}
return counter == 1;
}
- A.
1 if N is odd, otherwise 0
- B.
1 if N is a power of 2, otherwise 0
- C.
1 if the binary representation of N is all 1's, otherwise 0
- D.
1 if the binary representation of N has any 1's, otherwise 0
Attempted by 289 students.
Show answer & explanation
Correct answer: B
Conclusion: The function returns 1 when the unsigned integer N has exactly one '1' bit in its binary representation (i.e., N is a power of two). It returns 0 otherwise. Note that N = 0 yields 0 because there are no set bits.
What the loop does: On each iteration, counter += N & 1 adds 1 if the least significant bit of N is 1, otherwise adds 0. Then N = N >> 1 shifts N right to examine the next bit.
After the loop finishes, counter equals the total number of 1 bits in the original N.
The return statement return counter == 1; yields 1 if and only if exactly one bit was set. Exactly one set bit means N is a power of two (for unsigned N > 0).
Examples:
N = 8 (binary 1000): counter becomes 1 -> function returns 1.
N = 6 (binary 110): counter becomes 2 -> function returns 0.
N = 0 (binary 0): counter is 0 -> function returns 0.
Hence the correct description is: 1 if N is a power of 2, otherwise 0.