Number of Steps to Reduce a Number to Zero - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: num = 14
Output: 6
💡 Note: Step-by-step: 14 → 7 → 6 → 3 → 2 → 1 → 0. Total of 6 steps.
Example 2 — Small Number
$ Input: num = 8
Output: 4
💡 Note: 8 → 4 → 2 → 1 → 0. All even numbers except the last step.
Example 3 — Edge Case
$ Input: num = 1
Output: 1
💡 Note: Only one step needed: 1 → 0

Constraints

  • 0 ≤ num ≤ 106

Visualization

Tap to expand
Number of Steps to Reduce a Number to Zero INPUT num = 14 Binary: 1110 1 1 1 0 8 4 2 1 14 is EVEN (ends in 0) Goal: Reduce to 0 Even: divide by 2 Odd: subtract 1 ALGORITHM STEPS 1 14 is even 14/2 = 7 2 7 is odd 7-1 = 6 3 6 is even 6/2 = 3 4 3 is odd 3-1 = 2 5 2 is even 2/2 = 1 6 1 is odd 1-1 = 0 Flow 14 | 7 | 6 | 3 | 2 | 1 | 0 Time: O(log n) | Space: O(1) FINAL RESULT Output: 6 OK - 6 steps total Steps Breakdown: Divisions 3 Subtracts 3 14 --> 7 --> 6 --> 3 --> 2 --> 1 --> 0 Reduced to zero! Key Insight: The number of steps equals: (number of bits - 1) + (number of 1-bits). For 14 = 1110 in binary, we have 4 bits total and 3 one-bits. Steps = (4-1) + 3 = 6. Each divide-by-2 shifts right, each subtract removes a 1-bit. This gives O(log n) time complexity with O(1) space - optimal for bit manipulation! TutorialsPoint - Number of Steps to Reduce a Number to Zero | Optimal Solution
Asked in
LeetCode 15 Microsoft 8
91.1K Views
Medium Frequency
~10 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen