Power of Two in C

In C programming, checking whether a number is a power of two is a common problem that can be solved efficiently using bitwise operations. A power of two is any number that can be expressed as 2n where n is a non-negative integer (1, 2, 4, 8, 16, 32, etc.).

Syntax

bool isPowerOfTwo(int n);
// Returns true if n is a power of 2, false otherwise

Algorithm

The key insight is that powers of two have a specific binary pattern − they have exactly one bit set to 1 (the MSB) and all other bits are 0. For example:

  • 16 = 10000 (binary)
  • 15 = 01111 (binary)
  • 16 & 15 = 10000 & 01111 = 00000 = 0

The expression n & (n-1) will return 0 if and only if n is a power of 2.

Example

Here's a complete implementation to check if numbers are powers of two −

#include <stdio.h>
#include <stdbool.h>

bool isPowerOfTwo(int n) {
    return (n > 0 && !(n & (n - 1)));
}

int main() {
    printf("%s
", isPowerOfTwo(16) ? "true" : "false"); printf("%s
", isPowerOfTwo(12) ? "true" : "false"); printf("%s
", isPowerOfTwo(1) ? "true" : "false"); printf("%s
", isPowerOfTwo(32) ? "true" : "false"); return 0; }
true
false
true
true

How It Works

The function works by checking two conditions:

  1. n > 0: Ensures the number is positive (powers of 2 are always positive)
  2. !(n & (n-1)): Uses bitwise AND to check if exactly one bit is set
Binary Representation 16 (power of 2): 1 0 0 0 0 15 (16-1): 0 1 1 1 1 16 & 15: 0 0 0 0 0 12 (not power of 2): 1 1 0 0 11 (12-1): 1 0 1 1 12 & 11: 1 0 0 0 ? 0

Key Points

  • Time complexity: O(1) - constant time operation
  • Space complexity: O(1) - no extra space required
  • The number 1 is considered a power of 2 (20 = 1)
  • Negative numbers and zero are not powers of 2

Conclusion

Using bitwise operations with n & (n-1) provides an elegant and efficient solution to check if a number is a power of two. This approach leverages the unique binary pattern of powers of two for optimal performance.

Updated on: 2026-03-15T12:38:24+05:30

997 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements