Friday, February 12, 2021

Number of steps to make a number zero.

Problem: Given a non-negative integer, return the number of steps to reduce it to zero. Here are the steps we need to follow:

  • If the current number is even, you have to divide it by 2
  • Otherwise, you have to subtract 1 from it.

Example:

Input: num = 5
Output: 4
Explanation: 
Step 1) 5 is odd; subtract 1 and obtain 4. 
Step 2) 4 is even; divide by 2 and obtain 2. 
Step 3) 2 is even; divide by 2 and obtain 1. 
Step 4) 1 is odd; subtract 1 and obtain 0.


Approach: We just follow the steps given in the problem statement and keep counting the number of steps we are taking.


Implementation in C#:

    public int NumberOfSteps (int num) 

    {           

        int count = 0;  

        while (num != 0)

        {

            ++count;

            num = num % 2 == 0 ? num / 2 : num - 1; 

        }

        return count;

    }


Complexity: O(logn)

No comments:

Post a Comment