Power of Two Check in C

Level 4223 keystrokes

Uses bitwise AND to efficiently check if a number is a power of two.

C code

// Function to check if n is power of 2
1int isPowerOf2(unsigned int n) {
// A power of 2 has exactly one bit set; n > 0 rules out 0
// n & (n-1) clears the lowest set bit
// If result is 0, n had only one bit set
2 return n > 0 && (n & (n - 1)) == 0;
3}
// 16 = 10000 in binary (power of 2)
4printf("16: %s\n", isPowerOf2(16) ? "Yes" : "No");
// 15 = 01111 in binary (not power of 2)
5printf("15: %s\n", isPowerOf2(15) ? "Yes" : "No");
// 32 = 100000 in binary (power of 2)
6printf("32: %s\n", isPowerOf2(32) ? "Yes" : "No");

Output

16: Yes
15: No
32: Yes
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • "× 18
  • (× 9
  • )× 9
  • :× 6
  • ;× 4
  • ,× 3
  • ?× 3
  • \× 3
  • &× 3
  • %× 3

More C examples at level 4

← C typing practice