Power of Two
Easy About 8 min Free, no account needed
One bit trick, two edge cases waiting to bite.
The brief
Return true when n is a power of two (1, 2, 4, 8, ...).
The famous trick, a power of two has exactly one set bit, so
(n & (n - 1)) == 0, is only half the answer: it also accepts zero, and
on long.MinValue the subtraction wraps. Guard n > 0 first. The visible
tests are friendly; the hidden ones are exactly those two values (and a big
genuine power).
Starter code
using System;
public class Solution
{
// TODO: return true when n is a power of two.
public bool IsPowerOfTwo(long n)
{
throw new NotImplementedException();
}
}How it is graded
Visible examples help you iterate. Hidden tests then cover edge cases and larger inputs, and every test reports server-measured time and allocated bytes.
What it practices
- Bit manipulation
- Use masks, shifts and XOR on the binary representation directly.
Related katas
- Counting Bits Easy Free Popcounts for 0..n - reuse the table you are already building.
- Reverse Bits Easy Free Reverse a 32-bit pattern - signed shifts will betray you.
- Single Number Easy Free One value appears an odd number of times - XOR finds it for free.
- Gray Code at an Index Medium Free The n-th Gray code without generating the first n-1.