1342. Number of Steps to Reduce a Number to Zero | LeetCode | Python | Solution

Here is the link to this problem. Read the problem description carefully before solving this problem.

It’s an easy Leetcode problem. Here we will be given a non-negative number. We have to reduce the number based on some requirements until it gets zero. And then have to return how many steps it takes.

To reduce the number, we need to remember two things. If the current number is even, we will divide it by 2. If it’s not, we will subtract it by 1.

For example, our given number is 5. Then we will do something like below.

Step 1
5 is not even
5 – 1 = 4

Step 2
4 is even
4 / 2 = 2

Step 3
2 is even
2 / 2 = 1

Step 4
1 is not even
1 – 1 = 0

Answer = 4

Coding Part

To solve this problem, first, we will declare a variable for store the steps. Then we will run a while loop until the number does not get 0. Inside the loop, we will check the conditions and then increase the steps by 1.
After the loop, we will return the variable.

Let’s see the solution for better understanding. I know my code explains better than me. 🙂

class Solution:
    def numberOfSteps (self, num: int) -> int:
        steps = 0
        while num > 0:
            if num % 2 == 0:
                num /= 2
                num -= 1
            steps += 1
        return steps

That was my solution. There are many different types of solutions to this problem. Maybe those are better than this one. You can also try those solutions.

Happy coding 🙂
Keep practicing 🙂