Sponsored
Sponsored
The idea is to use a recursive function to determine the minimum number of operations needed to reduce the given number n
to 0. Consider each bit change step as a recursive call, effectively exploring the tree of possibilities until we reach 0.
We need to account for the operation rules defined in the problem, particularly handling the change in the i-th
bit when needed.
Time Complexity: O(log n), where n is the input size.
Space Complexity: O(log n), due to the recursion stack.
1def minimum_one_bit_operations(num):
2 if num == 0:
3 return 0
4 x = 1
5 bit = 0
6 while (x << 1) <= num:
7 x <<= 1
8 bit += 1
9 return minimum_one_bit_operations(num ^ x) + (1 << bit)
10
11n = 6
12print(minimum_one_bit_operations(n))
The Python function uses recursion, identifying the bit to manipulate using shifts and XOR operations.
This approach removes recursion and implements the bit operations iteratively. The key step involves simulating the recursive logic using a while loop and maintaining a transformation count.
Time Complexity: O(log n)
Space Complexity: O(1)
1
public class Program {
public static int MinimumOneBitOperations(int num) {
int res = 0;
while (num > 0) {
res ^= num;
num >>= 1;
}
return res;
}
public static void Main() {
int n = 6;
Console.WriteLine(MinimumOneBitOperations(n));
}
}
This C# method uses iterative logic with bitwise operations to deduce the number of steps required.