#2749
Minimum Operations to Make the Integer Zero
MediumBit ManipulationBrainteaserEnumerationBit ManipulationDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(log n)Space O(1)
The optimal solution leverages the properties of binary representation and the constraints of the problem. By focusing on the bits of num1 and how they interact with num2, we can minimize operations effectively.
⚙️
Algorithm
5 steps- 1Step 1: Calculate the effective value of num2 as num2 + 1.
- 2Step 2: If num1 is less than or equal to num2, return -1 as we cannot reach zero.
- 3Step 3: Count the number of bits set in num1 (this gives a lower bound on operations).
- 4Step 4: Check if the sum of num1 and num2 is even; if not, return -1 since we cannot reach zero with odd adjustments.
- 5Step 5: Return the number of bits set in num1 as the minimum operations needed.
solution.py9 lines
1# Full working Python code
2
3def min_operations(num1, num2):
4 num2 += 1
5 if num1 <= num2:
6 return -1
7 if (num1 + num2) % 2 != 0:
8 return -1
9 return bin(num1).count('1')ℹ
Complexity note: The complexity is logarithmic because we only need to count the bits in num1, which is proportional to the number of bits in its binary representation.
- 1Understanding how binary representation works can significantly reduce the number of operations needed.
- 2The relationship between num1 and num2 is crucial; if num1 is too small relative to num2, reaching zero becomes impossible.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.