Solving Leetcode Interviews in Seconds with AI: Minimum Operations to Reduce an Integer to 0
Introduction
In this blog post, we will explore how to solve the LeetCode problem "2571" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
You are given a positive integer n, you can do the following operation any number of times: Add or subtract a power of 2 from n. Return the minimum number of operations to make n equal to 0. A number x is power of 2 if x == 2i where i >= 0. Example 1: Input: n = 39 Output: 3 Explanation: We can do the following operations: - Add 20 = 1 to n, so now n = 40. - Subtract 23 = 8 from n, so now n = 32. - Subtract 25 = 32 from n, so now n = 0. It can be shown that 3 is the minimum number of operations we need to make n equal to 0. Example 2: Input: n = 54 Output: 3 Explanation: We can do the following operations: - Add 21 = 2 to n, so now n = 56. - Add 23 = 8 to n, so now n = 64. - Subtract 26 = 64 from n, so now n = 0. So the minimum number of operations is 3. Constraints: 1 <= n <= 105
Explanation
Here's the approach to solve this problem, followed by the code:
- Key Idea: The optimal strategy is to repeatedly bring
ncloser to the nearest power of 2 (either greater or smaller). This is because powers of 2 are the only operations allowed. - Greedy Approach: At each step, determine which power of 2 is closest to the current value of
n. Add or subtract that power to move closer to zero. Bit Manipulation: We can efficiently find the nearest powers of 2 using bit manipulation.
Runtime Complexity: O(log n). Storage Complexity: O(1).
Code
def min_operations(n: int) -> int:
"""
Calculates the minimum number of operations to make n equal to 0 by adding or subtracting powers of 2.
Args:
n: A positive integer.
Returns:
The minimum number of operations.
"""
operations = 0
while n > 0:
msb = n.bit_length()
lower_power_of_2 = 1 << (msb - 1)
upper_power_of_2 = 1 << msb
if n == lower_power_of_2:
n -= lower_power_of_2
else:
diff_lower = n - lower_power_of_2
diff_upper = upper_power_of_2 - n
if diff_lower <= diff_upper:
n -= lower_power_of_2
else:
n += lower_power_of_2
operations += 1
return operations