All mock tests are FREE till 31 December — register to save your progress

What does the following C function f() return?

int f(unsigned int N) {
  unsigned int counter = 0;
  while (N > 0) {
    counter += N & 1;
    N = N >> 1;
  }
  return counter == 1;
}

Pick an option to check yourself, or open the answer below.

Show answer & explanation

Correct answer: B. 1 if N is a power of 2 , otherwise 0

Explanation

The loop counts the 1 bits of N, and the function returns whether that count is exactly 1 — true exactly when N is a power of 2.

More Programming Languages and Computer Graphics questions