Number of Steps to Reduce a Number to Zero

You’re given an integer num, and you want to reduce it to zero. If the number is even, divide it by 2; if it’s odd, subtract 1 from it. Continue this process until the number becomes zero, and return the number of steps taken to do so.

Here’s the code that encapsulates the above logic:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
    def numberOfSteps(self, num: int) -> int:
        steps = 0
        while num > 0:
            if num % 2 == 0:
                num //= 2
            else:
                num -= 1
            steps += 1
        return steps

Explanation

  1. Initialize Steps: We keep track of the number of steps taken using the steps variable.

  2. Loop Until num is Zero: We continue the process as long as num is greater than zero.

  3. Even/Odd Check: Inside the loop, we check if the number is even or odd. If it’s even, we divide it by 2; if it’s odd, we subtract 1.

  4. Increment Steps: For each operation (either division by 2 or subtraction of 1), we increment the steps variable by 1.

  5. Return the Result: Finally, we return the total number of steps taken.

Example

For num = 14, the function will follow these steps:

  • Divide 14 by 2 (even) → 7
  • Subtract 1 from 7 (odd) → 6
  • Divide 6 by 2 (even) → 3
  • Subtract 1 from 3 (odd) → 2
  • Divide 2 by 2 (even) → 1
  • Subtract 1 from 1 (odd) → 0

Total steps: 6, so the function returns 6.