A power of two has exactly one set bit. Using Brian Kernighan's trick: if n & (n - 1) == 0, then has at most one set bit.
But we also need (since has no set bits but isn't a power of two).
The check is: n > 0 && (n & (n - 1)) == 0.
A power of two has exactly one set bit. Using Brian Kernighan's trick: if n & (n - 1) == 0, then has at most one set bit.
But we also need (since has no set bits but isn't a power of two).
The check is: n > 0 && (n & (n - 1)) == 0.