Easy 0 solved 0% acceptance

Power of Two

Check whether a number is a power of two.

What you'll learn

  • Check powers of two by repeated halving
  • Use the n & (n - 1) bit trick
  • Handle zero and negative numbers

Problem

Decide whether n equals 2ᵏ for some whole number k ≥ 0 (1, 2, 4, 8, …).

Implement is_power_of_two(n).

Input

n: The number to check.

Output

Return true if n is a power of two.

Constraints

-10¹⁸ ≤ n ≤ 10¹⁸

Examples

Example 1
Input:
n = 64

Expected output:
expected = True
Input:
long long n = 64;

Expected output:
bool expected = true;
Input:
long n = 64;

Expected output:
bool expected = true;

Explanation

64 = 2⁶.

Example 2
Input:
n = 12

Expected output:
expected = False
Input:
long long n = 12;

Expected output:
bool expected = false;
Input:
long n = 12;

Expected output:
bool expected = false;

Explanation

12 = 4 × 3 has an odd factor, so it is not a power of two.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

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

Hint 2

Check that the number is positive before using a bit-based test.

Hint 3

Negative numbers and zero are never powers of two.

Expected complexity

O(1) time, O(1) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.