Problem 1342

Abstract / Summary

Count the steps needed to turn a number into zero by repeatedly dividing by two and adding the remainder each time.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1342.py

class Solution:
    def numberOfSteps(self, num: int) -> int:
        result = 0
        while num > 0:
            result += num & 1
            num   >>= 1
            if num > 0:
                result += 1
        return result
9 lines | 241 bytes | submitted December 12, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 86% (1+ million submissions).

Typical patterns to solve this problem:
  • Bit Manipulation
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided Solution class implements a method numberOfSteps that computes the number of operations required to reduce a non-negative integer to zero. The reduction follows a rule set where each iteration either removes the least-significant set bit or performs a single right shift, effectively counting the steps needed to clear all bits. The implementation relies exclusively on bitwise operators and a simple loop, delivering a compact and efficient solution.

Key Steps

Initialization

The method begins by establishing a counter named result set to zero. This counter accumulates the total number of steps taken throughout the execution.

result = 0

Loop Condition

A while loop drives the process, continuing as long as the input num remains greater than zero. This condition guarantees that the loop terminates precisely when all bits have been cleared.

while num > 0:

Bitwise Accumulation

Inside the loop, the expression num & 1 extracts the least-significant bit of num. Adding this value to result accounts for a step when the current bit is set (i.e., when the number is odd).

result += num & 1

Shift Operation

The statement num >>= 1 performs a right arithmetic shift, discarding the least-significant bit that has just been examined. This operation effectively divides the number by two without using division, preparing the next iteration to examine the new least-significant bit.

num >>= 1

Conditional Increment

After the shift, the code checks whether any bits remain (num > 0). If so, it adds one more to result. This extra increment represents the step of performing the shift itself, which is counted only when there is still work to do.

if num > 0:
    result += 1

Return Value

When the loop exits, result holds the total count of steps required to reduce the original number to zero, and the method returns this value.

return result

Edge Cases Handled

When the input num is zero, the loop condition while num > 0 fails immediately, leaving result at its initial value of zero. This correctly reflects that no steps are needed for an already zero value.

For numbers that are powers of two, the binary representation contains a single set bit followed by zeros. The loop processes the single set bit, adds one for the bit removal, then performs successive right shifts. The conditional increment ensures that each shift is counted until the number becomes zero, accurately capturing the total steps for such inputs.

Odd numbers trigger the result += num & 1 line on every iteration because the least-significant bit is always one. The subsequent shift removes that bit, and the conditional increment adds the cost of the shift, handling the alternating pattern of subtraction and division that characterizes odd inputs.

Even numbers skip the addition from num & 1 because the least-significant bit is zero, but they still incur a step for the shift via the conditional increment, correctly modeling the division-by-two operation without an explicit subtraction step.

Performance Optimizations

The algorithm leverages bitwise operators (& and >>) instead of arithmetic operations such as modulo or division. Bitwise operations execute in constant time on modern processors, providing a speed advantage over higher-level arithmetic.

By combining the detection of a set bit and the shift into a single loop iteration, the code minimizes the number of loop cycles needed to process each bit. The conditional increment after the shift avoids an unnecessary addition when the number has already reached zero, preventing a superfluous step count.

The use of a single integer variable for the accumulator and the in-place modification of num reduces memory overhead and improves cache locality, contributing to overall efficiency. The straightforward control flow eliminates function calls or recursion, ensuring that the execution path remains tight and predictable.

written by openai gpt

ELI5 - Simplified Explanation

Imagine there is a magical toy box filled with building blocks. The goal is to make the toy box completely empty. To do this, a special robot follows two simple rules. If the number of blocks in the box is an odd number, the robot takes one single block out and sets it aside. If the number of blocks is an even number, the robot takes half of the blocks away at once. Every single time the robot performs one of these actions, a counter tracks it like a scorekeeper marking down each step. The robot keeps looking into the box and repeating these actions until there are no blocks left inside. This code tracks the count of those actions to tell how many steps it takes to reach zero.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 7.15 | σ = 1.81

Complexity Analysis

Time: logarithmic
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go Rust TS
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fpdjsns C++
fsq C++
JoshCrozier JS
Krazune C++
lkwq007 Python
qiyuangong Python
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fpdjsns C++
fsq C++
JoshCrozier JavaScript
Krazune C++
lkwq007 Python
qiyuangong Python
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
32 links | 20 authors | 10 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

17 solutions   December 12, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality