Number of Steps to Reduce a Number to Zero
Easy
Topics
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
Input: n = 14 Output: 6
Example 2
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
- 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 != 0with 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
-1omitted, or applying it ton = 0where 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 stepsimport java.util.*;
class Solution {
public int numberOfSteps(int n) {
int steps = 0;
while (n > 0) {
if (n % 2 == 0) n /= 2;
else n -= 1;
steps++;
}
return steps;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int numberOfSteps(int n) {
int steps = 0;
while (n > 0) {
if (n % 2 == 0) n /= 2;
else n -= 1;
steps++;
}
return steps;
}
};/**
* @param {number} n
* @return {number}
*/ var numberOfSteps = function(n) {
let steps = 0;
while (n > 0) {
if (n % 2 === 0) n /= 2;
else n -= 1;
steps++;
}
return steps;
};