Problème
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
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⁶.
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.