Power of Two
Given an integer n, return True if it is a power of two.
Example
16
True
- Input:
nis a single integer, here16. It can be any 32-bit signed value, so zero and negative numbers are valid inputs too. - The math:
nis a power of two when for some whole number . For the sample, , so and the answer isTrue. - Contrast: is not, because its factorisation contains an odd factor other than . Likewise sits between and , which gives
False. - Edges to notice: counts, so
1givesTrue. Every is strictly positive, so and all negative inputs (even ) giveFalse. - Output: a single boolean,
Truefor the sample. Notice that the powers of two thin out fast: there are only 31 of them in the whole input range, from up to .
Constraints
- -2^31 <= n <= 2^31 - 1