1. Must be positive
Zero and negatives are never powers of two.
n > 0Typorithm · easy
Step 1 of 8 · intro card
Bit Manipulation
A power of two has exactly one set bit, so n > 0 and n & (n-1) === 0 identifies it.
Powers of two are 1, 2, 4, 8... each with a single 1 bit in binary.
Clearing the lowest set bit of such a number leaves zero, since there is only one bit.
Guarding with n > 0 rules out zero and negatives.
Exactly one set bit.
n & (n-1) === 0 clears it to zero.
Require n > 0.
function isPowerOfTwo(n) {
return n > 0 && (n & (n - 1)) === 0;
}Connect each part of the code to the concept before you type.
Zero and negatives are never powers of two.
n > 0A power of two has exactly one set bit, so clearing it yields zero.
(n & (n - 1)) === 0Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputUnsigned n = 13
Follow temporary values, local state and supporting structures at this step.
Count1 entries
Local state · indices and saved values
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state