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.
1using System;
2
3public class Program {
4 public static int MinimumOneBitOperations(int num) {
5 if (num == 0) return 0;
6 int x = 1, bit = 0;
7 while ((x << 1) <= num) {
8 x <<= 1;
9 bit++;
10 }
11 return MinimumOneBitOperations(num ^ x) + (1 << bit);
12 }
13
14 public static void Main() {
15 int n = 6;
16 Console.WriteLine(MinimumOneBitOperations(n));
17 }
18}
The C# method is a direct implementation of recursive strategy using bitwise operations for efficiency.
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
In Java, the loop iterates through the bits of num
, using XOR to accumulate the result iteratively.