Educatifu
Open menu

Power of Two

Easybit-manipulationmath

Decide whether a positive integer is an exact power of two (1, 2, 4, 8, 16, …).

Input

A single positive integer n.

Output

true if n is a power of two, otherwise false.

Examples

Example 1

Input
1
Output
true

1 is 2^0.

Example 2

Input
16
Output
true

16 is 2^4.

Example 3

Input
18
Output
false

18 = 10010 in binary — two bits set.

Constraints

  • 1 <= n <= 10^18

Hints

Reveal hint 1

A power of two has exactly one bit set in binary.

Reveal hint 2

For a power of two, n AND (n-1) clears that one bit and leaves 0.

Reference solution (spoiler — try it yourself first)

Approach

A power of two has a single set bit, so n > 0 and (n & (n - 1)) == 0.

n = int(input())
print("true" if n > 0 and (n & (n - 1)) == 0 else "false")

← All practice problems

Bring us the problem, not a perfect specification

Tell us what needs to change, who it affects and any important deadline. We will review the context and reply with useful next questions.

  1. 01Share contextDescribe the workflow, constraint or risk.
  2. 02Clarify togetherWe identify missing facts and useful options.
  3. 03Choose a startAgree a focused assessment or delivery step.
Start a conversation