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:


Explanation
Initialize Steps: We keep track of the number of steps taken using the
steps
variable.Loop Until num is Zero: We continue the process as long as
num
is greater than zero.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.
Increment Steps: For each operation (either division by 2 or subtraction of 1), we increment the
steps
variable by 1.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
.