← Back to libraryQuestion 79 of 273
⌨️Java CodingBeginner

Check if a Number is a Power of Two

📌 Definition:

Determine whether a positive integer is a power of two (1, 2, 4, 8, 16, ...).

📖 Detailed Explanation:

A power of two has exactly one set bit, so n & (n - 1) == 0 for positive n. Guard n > 0 (zero and negatives are not powers of two). This is O(1) and far slicker than dividing by 2 in a loop.

💻 Solutions:
public static boolean isPowerOfTwo(int n) {
    return n > 0 && (n & (n - 1)) == 0;
}
function isPowerOfTwo(n) {
  return n > 0 && (n & (n - 1)) === 0;
}
def is_power_of_two(n):
    return n > 0 and (n & (n - 1)) == 0
🔑 Key Points:
  • A power of two has exactly one set bit
  • n > 0 && (n & (n-1)) == 0
  • O(1) bit trick beats the divide loop
  • Guard zero and negatives
🌍 Real-World Example:

Power-of-two checks matter for buffer/allocation sizing and hash-table capacities; the bit trick is a staple senior-level shortcut.

🎯 Scenario-Based Interview Question:

A candidate loops dividing by 2. What is the O(1) alternative and why does it work?