Number of Steps to Reduce a Number to Zero

Easy

Topics
MathBit Manipulation

Given an integer n, return the number of steps to reduce it to zero. In one step, if the number is even divide it by two, otherwise subtract one.

Example 1

765432101400001110700000111600000110300000011200000010100000001
Even numbers halve (a right shift) and odd numbers lose one (clearing the last bit), so the count is just bits + set bits − 1: 6 steps for 14. Each row is one step.
Cells are the binary expansion, most significant bit on the left; the small numbers are bit positions.
Input:  n = 14
Output: 6

Example 2

76543210800001000400000100200000010100000001
Input:  n = 8
Output: 4

Example 3

Input:  n = 0
Output: 0

Constraints

  • 0 <= n <= 10^6
Editorial — intuition, approach, complexity and pitfalls

Intuition

Even numbers are halved, odd numbers decremented, counting steps until zero. Simulating that directly is O(log n) because halving shrinks the number geometrically and a decrement is always immediately followed by a halving.

In bit terms the process is transparent: halving is a right shift, and decrementing an odd number clears its lowest bit. So the total is one step per bit (the shifts) plus one extra per set bit (the decrements) — precisely bit_length + popcount - 1, the -1 because the leading 1 is cleared by a decrement rather than shifted away. Worth knowing as the closed form, though the simulation is clearer and the same complexity.

Approach

  1. While n > 0: halve if even, else subtract 1; count each.

Dry Run

n = 14  (1110)

14 even -> 7     step 1
 7 odd  -> 6     step 2
 6 even -> 3     step 3
 3 odd  -> 2     step 4
 2 even -> 1     step 5
 1 odd  -> 0     step 6

answer 6

closed form: 14 has bit_length 4 and popcount 3
             4 + 3 - 1 = 6  ✓

Complexity

  • Time — O(log n): at most two steps per bit.
  • Space — O(1).

Common Pitfalls

  • Looping on n != 0 with a signed type and a path that can go negative. Not reachable here, but the guard should be > 0.
  • Counting only the halvings, or only the decrements.
  • Using the closed form with the -1 omitted, or applying it to n = 0 where it does not hold.
  • Converting to a binary string and counting characters. It works, but it allocates to answer a question two arithmetic operations settle.

Full Solution — all languages

class Solution:
    def numberOfSteps(self, n):
        steps = 0
        while n > 0:
            if n % 2 == 0:
                n //= 2
            else:
                n -= 1
            steps += 1
        return steps
SensAI
Beta
Tap the mic to stop voice mode