Sponsored
Sponsored
Solve with full IDE support and test cases
This approach involves using bit manipulation to find out which bits are different between the XOR of the array and k. For each differing bit, calculate the minimum number of flips needed across all elements to switch that bit in the resultant XOR.
Time Complexity: O(n), where n is the length of the array, since we only traverse it twice.
Space Complexity: O(1), as no additional data structures are used.
1using System;
2
3class Solution {
4 public int MinOperations(int[] nums, int k) {
5 int xorSum = 0;
6 for (int i = 0; i < nums.Length; i++) {
7 xorSum ^= nums[i];
8 }
9 int diff = xorSum ^ k;
10 int operations = 0;
11 while (diff != 0) {
12 operations += diff & 1;
13 diff >>= 1;
14 }
15 return operations;
16 }
17
18 static void Main(string[] args) {
19 int[] nums = { 2, 1, 3, 4 };
20 int k = 1;
21 Solution solution = new Solution();
22 Console.WriteLine(solution.MinOperations(nums, k));
23 }
24}
This C# program calculates minimum bit flips by first computing the XOR of all elements and then finding differing bits from k.
In this approach, the focus is on counting the set bits of two numbers (XOR sum and k) - i.e., how many bits are 1 in their binary representation. We aim to equalize the set bits count by flipping specific bits in nums.
Time Complexity: O(n + log(max(nums[i])))
Space Complexity: O(1).
1
class Solution {
public int CountSetBits(int n) {
int count = 0;
while (n != 0) {
count += n & 1;
n >>= 1;
}
return count;
}
public int MinOperations(int[] nums, int k) {
int xorSum = 0;
foreach (int num in nums) {
xorSum ^= num;
}
int setBitsXor = CountSetBits(xorSum);
int setBitsK = CountSetBits(k);
return Math.Abs(setBitsXor - setBitsK);
}
static void Main(string[] args) {
int[] nums = { 2, 1, 3, 4 };
int k = 1;
Solution solution = new Solution();
Console.WriteLine(solution.MinOperations(nums, k));
}
}
This C# code counts the number of set bits in both the XOR sum and k, and uses the difference to determine the minimum number of flips needed.