#1611

Minimum One Bit Operations to Make Integers Zero

Hard
MathDynamic ProgrammingBit ManipulationRecursionMemoizationBit ManipulationDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(log n)
Space
O(1)
O(1)
💡

Intuition

Time O(log n)Space O(1)

The optimal approach leverages the observation that we can clear bits more efficiently by focusing on the leftmost set bit and counting the necessary operations to clear each bit in sequence.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a counter for operations.
  2. 2Step 2: While n is greater than 0, find the leftmost set bit.
  3. 3Step 3: Count how many bits are to the right of this bit (including the bit itself).
  4. 4Step 4: Increment the operations counter by the number of bits counted.
  5. 5Step 5: Clear the leftmost set bit and repeat until n is zero.
solution.py13 lines
1# Full working Python code
2
3def min_operations(n):
4    operations = 0
5    while n > 0:
6        leftmost_bit = n.bit_length() - 1
7        operations += leftmost_bit + 1
8        n &= ~(1 << leftmost_bit)
9    return operations
10
11# Example usage
12print(min_operations(3))  # Output: 2
13print(min_operations(6))  # Output: 4

Complexity note: The time complexity is O(log n) because we only need to process each bit of n, which is proportional to the number of bits in the binary representation of n.

  • 1Understanding bit manipulation is crucial for optimizing operations on integers.
  • 2Recognizing patterns in binary representation can significantly reduce the number of operations needed.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.