Problème
Repeatedly divide n by 2, dropping any remainder (integer division), until it becomes 1. Count how many divisions that takes.
Implement halve_until_one(n).
Input
n: A positive integer.
Output
Return the number of divisions.
Contraintes
1 ≤ n ≤ 1,000,000,000,000
Exemples
Entrée :
n = 20
Sortie attendue :
expected = 4
Entrée :
long long n = 20;
Sortie attendue :
long long expected = 4;
Entrée :
long n = 20;
Sortie attendue :
long expected = 4;
Explication
20 → 10 → 5 → 2 → 1 takes 4 divisions.
Entrée :
n = 1
Sortie attendue :
expected = 0
Entrée :
long long n = 1;
Sortie attendue :
long long expected = 0;
Entrée :
long n = 1;
Sortie attendue :
long expected = 0;
Explication
n is already 1, so no divisions are needed.
Comment l'aborder
Essayez d'abord seul, puis ouvrez les indices un par un.
Indice 1
Count how many times you can shrink the number by dividing by two before it becomes one.
Indice 2
Repeated integer division is enough here; no need to track the discarded remainders.
Indice 3
Make sure you stop exactly when the value reaches one, not when it becomes zero.
Complexité attendue
O(log n) time, O(1) extra space
Références
Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.