Power of Two
Determining if a number is a power of two is a classic bit-manipulation problem. A power of two has exactly one bit set. The trick: n & (n-1) == 0 for n > 0.
Java implementation:
public static boolean isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0;
}
This works because subtracting 1 flips the lowest 1 bit and all lower bits; AND with original clears all bits except possibly the higher bits. For a power of two, only one bit is set, so n & (n-1) becomes 0.
Two Minute Drill
- Power of two: exactly one bit set.
- Check: n > 0 && (n & (n-1)) == 0.
- Common in problems involving binary representation.
Need more clarification?
Drop us an email at career@quipoinfotech.com
