問題
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.
制約
1 ≤ n ≤ 1,000,000,000,000
例
入力:
n = 20
期待される出力:
expected = 4
入力:
long long n = 20;
期待される出力:
long long expected = 4;
入力:
long n = 20;
期待される出力:
long expected = 4;
解説
20 → 10 → 5 → 2 → 1 takes 4 divisions.
入力:
n = 1
期待される出力:
expected = 0
入力:
long long n = 1;
期待される出力:
long long expected = 0;
入力:
long n = 1;
期待される出力:
long expected = 0;
解説
n is already 1, so no divisions are needed.
解き方のヒント
まずは自分で考えてから、ヒントを1つずつ開いてみましょう。
ヒント 1
Count how many times you can shrink the number by dividing by two before it becomes one.
ヒント 2
Repeated integer division is enough here; no need to track the discarded remainders.
ヒント 3
Make sure you stop exactly when the value reaches one, not when it becomes zero.
目安の計算量
O(log n) time, O(1) extra space
参考資料
この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。