Power of Two
Return 1 if target is two raised to a nonnegative integer power and 0 otherwise. The values list is unused.
Return 1 if target is two raised to a nonnegative integer power and 0 otherwise. The values list is unused.
Input and constraints
- Use at most 32 integers. Each numeric input is between -1000 and 1000.
Code inspector
def solve(values, target): if (target <= 0): return 0 remaining = (target & (target - 1)) if (remaining == 0): return 1 return 0Visualizer
Step 1 of 3Empty array
Reject a nonpositive target before inspecting bits
Reject a nonpositive target before inspecting bits.
Variable watch
Step explanation
Reject a nonpositive target before inspecting bits.
Worked explanation
A binary shelf label for a power of two lights exactly one switch.
Guided solution
A positive power of two has exactly one set bit. Clearing that bit produces zero.
O(1) for fixed-width inputs time · O(1) auxiliary space
Examples
Worked example · {"values":[],"target":16} ⇒ 1
Edge case 1 · {"values":[],"target":0} ⇒ 0
Edge case 2 · {"values":[],"target":12} ⇒ 0
Edge case 3 · {"values":[],"target":-2} ⇒ 0
Progressive hints
Hint 1
A binary shelf label for a power of two lights exactly one switch.Hint 2
A positive power of two has exactly one set bit. Clearing that bit produces zero.Hint 3
Step through the worked example and inspect the highlighted variables before each update.Common mistake
Zero also satisfies the mask equality and needs a separate positivity test.
Interview follow-up
How would you recognize a power of four?