Easy 0 solved 0% acceptance

Halve Until One

Count how many halvings bring a number down to 1.

What you'll learn

  • Loop until a condition is false
  • Count iterations
  • Use integer division

Problem

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.

Constraints

1 ≤ n ≤ 1,000,000,000,000

Examples

Example 1
Input:
n = 20

Expected output:
expected = 4
Input:
long long n = 20;

Expected output:
long long expected = 4;
Input:
long n = 20;

Expected output:
long expected = 4;

Explanation

20 → 10 → 5 → 2 → 1 takes 4 divisions.

Example 2
Input:
n = 1

Expected output:
expected = 0
Input:
long long n = 1;

Expected output:
long long expected = 0;
Input:
long n = 1;

Expected output:
long expected = 0;

Explanation

n is already 1, so no divisions are needed.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

Count how many times you can shrink the number by dividing by two before it becomes one.

Hint 2

Repeated integer division is enough here; no need to track the discarded remainders.

Hint 3

Make sure you stop exactly when the value reaches one, not when it becomes zero.

Expected complexity

O(log n) time, O(1) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.