Skip to content
Katabench
Try free

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 hidden trap

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

C#
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.

C# coding challenges →

What it practices

Bit manipulation
Use masks, shifts and XOR on the binary representation directly.

Related katas