ProgrammingHardHCL · Tech Mahindra pattern

What is printed? (Check if a number is a power of two.)

What is printed? (Check if a number is a power of two.)
int isPowerOfTwo(int n) {
    return n > 0 && (n & (n - 1)) == 0;
}
int main(void) {
    printf("%d %d %d %d", isPowerOfTwo(16), isPowerOfTwo(18), isPowerOfTwo(1), isPowerOfTwo(0));
}
  1. A. 1 1 1 0
  2. B. 0 0 1 1
  3. C. 1 0 0 0
  4. D. 1 0 1 0

Correct answer: D. 1 0 1 0

n & (n-1) clears the lowest set bit; the result is 0 only when n had exactly one set bit (a power of two). 16 (10000) & 15 (01111) = 0 -> true. 18 (10010) & 17 (10001) = 10000 != 0 -> false. 1 (1) & 0 (0) = 0 -> true (2^0). 0 fails the n>0 check -> false.

More C Programming questions

Exams that ask this topic