Number of Steps to Reduce a Number to Zero LeetCode Solution

Problem – Number of Steps to Reduce a Number to Zero LeetCode Solution

Given an integer num, return the number of steps to reduce it to zero.

In one step, 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.

Example 3:

Input: num = 123
Output: 12

Constraints:

  • 0 <= num <= 106

Number of Steps to Reduce a Number to Zero LeetCode Solution in C++

int numberOfSteps (int num) {
  return num == 0 ? 0 : log2(num) + bitset<32>(num).count();
}

Number of Steps to Reduce a Number to Zero LeetCode Solution in Python

class Solution:
    def numberOfSteps (self, num: int) -> int:
        bitstring = bin(num)[2:] # [2:] will remove the '0b' that is prepended to each bitstring by bin()
        return len(bitstring) - 1 + bitstring.count('1')

Number of Steps to Reduce a Number to Zero LeetCode Solution in Java

public int numberOfSteps (int num) {
	return Integer.toBinaryString(num).length() - 1 + Integer.bitCount(num);
}
Number of Steps to Reduce a Number to Zero LeetCode Solution Review:

In our experience, we suggest you solve this Number of Steps to Reduce a Number to Zero LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Number of Steps to Reduce a Number to Zero LeetCode Solution

Find on LeetCode

Conclusion:

I hope this Number of Steps to Reduce a Number to Zero LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions

Leave a Reply

Your email address will not be published. Required fields are marked *