563.Count Iterations When Multiplying by Two
Easy
For the loop
i = 1; while (i < n) { i *= 2; }, return how many times it runs.
Multiplying the loop variable is the mirror image of dividing it: instead of shrinking n towards 1, it grows i towards n, doublingExponential Growth of the Loop VariableBecause i doubles each pass, it reaches n after only about log₂(n) passes. each time. Either way the loop runs about log₂(n) times, so loops like for (i = 1; i < n; i *= 2) are O(log n).
Example 1:
Input: n = 10
Output: 4
Example 2:
Input: n = 16
Output: 4
+ 5 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ n ≤ 1000000000
n =
10