Đề bài
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.
Ràng buộc
1 ≤ n ≤ 1,000,000,000,000
Ví dụ
Đầu vào:
n = 20
Kết quả mong đợi:
expected = 4
Đầu vào:
long long n = 20;
Kết quả mong đợi:
long long expected = 4;
Đầu vào:
long n = 20;
Kết quả mong đợi:
long expected = 4;
Giải thích
20 → 10 → 5 → 2 → 1 takes 4 divisions.
Đầu vào:
n = 1
Kết quả mong đợi:
expected = 0
Đầu vào:
long long n = 1;
Kết quả mong đợi:
long long expected = 0;
Đầu vào:
long n = 1;
Kết quả mong đợi:
long expected = 0;
Giải thích
n is already 1, so no divisions are needed.
Hướng tiếp cận
Hãy tự thử trước, sau đó mở từng gợi ý một.
Gợi ý 1
Count how many times you can shrink the number by dividing by two before it becomes one.
Gợi ý 2
Repeated integer division is enough here; no need to track the discarded remainders.
Gợi ý 3
Make sure you stop exactly when the value reaches one, not when it becomes zero.
Độ phức tạp mong đợi
O(log n) time, O(1) extra space
Tham khảo
Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.