ProgrammingVery hardGATE CS · Campus placements

Which function correctly tests whether an unsigned value x is a power of two, with x = 0 excluded?

  1. A. return x & (x - 1) == 0;
  2. B. return (x & (x - 2)) == 0;
  3. C. return x && !(x & (x - 1));
  4. D. return x == 0 || (x & (x - 1)) == 0;

Correct answer: C. return x && !(x & (x - 1));

x & (x - 1) is zero for every power of two, but it is also zero for x = 0 after wrapping. The first form parses as x & ((x-1) == 0), which is wrong for nearly every input, and the last form accepts 0, so only the third is correct.

More C Programming questions

Exams that ask this topic