v9.1.1
Menu

Power of Two

easyFREEMath & Bit ManipulationDSA for AI Engineers

Given an integer n, return True if it is a power of two.

Example

Input
16
Output
True
Reasoning
  • Input: n is a single integer, here 16. It can be any 32-bit signed value, so zero and negative numbers are valid inputs too.
  • The math: n is a power of two when n=2kn = 2^k for some whole number k≥0k \ge 0. For the sample, 16=2×2×2×2=2416 = 2 \times 2 \times 2 \times 2 = 2^4, so k=4k = 4 and the answer is True.
  • Contrast: 12=22×312 = 2^2 \times 3 is not, because its factorisation contains an odd factor other than 11. Likewise 33 sits between 21=22^1 = 2 and 22=42^2 = 4, which gives False.
  • Edges to notice: 1=201 = 2^0 counts, so 1 gives True. Every 2k2^k is strictly positive, so 00 and all negative inputs (even −16-16) give False.
  • Output: a single boolean, True for the sample. Notice that the powers of two thin out fast: there are only 31 of them in the whole input range, from 202^0 up to 2302^{30}.

Constraints

  • -2^31 <= n <= 2^31 - 1

More from DSA for AI Engineers

solution.py

Test results

Sign in to run your code against the test cases.