Given a non-negative integer, repeatedly subtract 1 from odd numbers and divide even numbers by 2 until the value becomes zero. Return the number of operations needed.
Number of Steps to Reduce a Number to Zero
You are given a non-negative integer num.
Repeat the following process until num becomes 0:
- If
numis even, replace it withnum / 2. - If
numis odd, replace it withnum - 1.
Return the total number of operations performed.
This is a straightforward process problem that can be solved by simulating the steps directly or by observing how binary parity affects the count.
Input Format
- A single integer
num. numis non-negative.
Output Format
- Return an integer: the number of steps required to reduce
numto0.
Constraints
- The answer fits in a 32-bit signed integer.
Example 1
Input
num = 14
Output
6
Explanation
14 is even -> 7, odd -> 6, even -> 3, odd -> 2, even -> 1, odd -> 0. Total steps = 6.
Example 2
Input
num = 8
Output
4
Explanation
8 -> 4 -> 2 -> 1 -> 0, so the number of steps is 4.
Show 1 more example
Example 3
Input
num = 0
Output
0
Explanation
The number is already zero, so no operations are needed.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.