Start learning free

LESSON 206 OF 505 · WHILE LOOPS - CHALLENGES

Halving Steps in Scala

Practice

Given a positive integer n, return how many times you have to divide it by 2 until it becomes 1.

Every division is an integer division: the remainder is dropped, so 9 divided by 2 gives 4. Keep dividing the new value by 2 until it is 1, and count the divisions. If n is already 1, no division is needed.

 

Example 1:

Input: n = 8
Output: 3
Explanation: 8 → 4 → 2 → 1: three divisions by 2.

Example 2:

Input: n = 9
Output: 3
Explanation: 9 → 4 → 2 → 1. 9 divided by 2 gives 4, because the remainder 1 is dropped.

Example 3:

Input: n = 1
Output: 0
Explanation: n is already 1, so there is nothing to divide.

 

Constraints:

  • 1 <= n <= 109
STEP 1 OF 6
    Ctrl + Enter to check

    Halving Steps in Scala

    Keep going with Scala500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free