Determine whether a positive integer is a power of two (1, 2, 4, 8, 16, ...).
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.
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)) == 0Power-of-two checks matter for buffer/allocation sizing and hash-table capacities; the bit trick is a staple senior-level shortcut.
A candidate loops dividing by 2. What is the O(1) alternative and why does it work?