Facile 0 résolus 0 % de réussite

Power of Two

Check whether a number is a power of two.

Ce que vous allez apprendre

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

Problème

Afficher la traduction

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.

Contraintes

-10¹⁸ ≤ n ≤ 10¹⁸

Exemples

Exemple 1
Entrée :
n = 64

Sortie attendue :
expected = True
Entrée :
long long n = 64;

Sortie attendue :
bool expected = true;
Entrée :
long n = 64;

Sortie attendue :
bool expected = true;

Explication

64 = 2⁶.

Exemple 2
Entrée :
n = 12

Sortie attendue :
expected = False
Entrée :
long long n = 12;

Sortie attendue :
bool expected = false;
Entrée :
long n = 12;

Sortie attendue :
bool expected = false;

Explication

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

Comment l'aborder

Essayez d'abord seul, puis ouvrez les indices un par un.

Indice 1

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

Indice 2

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

Indice 3

Negative numbers and zero are never powers of two.

Complexité attendue

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

Références

Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.

Apprenez des autres

Solutions de la communauté

Aucune solution publiée pour l'instant. Résolvez ce défi pour partager la première.