Number of Steps to Reduce a Number to Zero LeetCode Solution - The Coding Shala

Home >> LeetCode >> Number of Steps to Reduce a Number to Zero

 In this post, we will learn how to solve LeetCode's Number of Steps to Reduce a Number to the Zero problem and will implement its solution in Java.

Number of Steps to Reduce a Number to Zero Problem

Given a non-negative integer num, return the number of steps to reduce it to zero. If the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.

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

Example 2:
Input: num = 8
Output: 4
Explanation: 
Step 1) 8 is even; divide by 2 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.

Number of Steps to Reduce a Number to Zero Java Solution

Approach 1

Using loop.

Time Complexity: O(n)

Java Program: 

class Solution {
    public int numberOfSteps (int num) {
        int steps = 0;
        while(num != 0) {
            if(num%2 == 0) num /= 2;
            else num--;
            steps++;
        }
        return steps;
    }
}

Approach 2

Using bitwise operation.

To count steps we will do the right shift. For odd numbers we need two steps and for even need one step.

Java Program: 

class Solution {
    public int numberOfSteps (int num) {
        if(num <= 0 ) return 0;
        int steps = 0;
        while(num != 0) {
            int chk = num & 1;
            if(chk == 0) steps += 1;  //for even
            else steps += 2;  //for odd
            num = num >> 1;
        }
        //reduce one from last 1 numer as we only need 1 step for 1.
        return steps - 1;
    }
}


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

  1. what about https://medium.com/avi-parshan-studios/number-of-steps-to-reduce-a-number-to-zero-coding-interview-question-in-java-1a92fe414ea1

    ReplyDelete

Post a Comment

Popular Posts from this Blog

Anti Diagonals - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

LeetCode - Bulb Switcher Solution - The Coding Shala

New Year Chaos Solution - The Coding Shala

Sorting the Sentence LeetCode Solution - The Coding Shala