Skip to content

Commit 62f1c79

Browse files
committed
Add solution #2997
1 parent 27782c8 commit 62f1c79

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2115,6 +2115,7 @@
21152115
2976|[Minimum Cost to Convert String I](./solutions/2976-minimum-cost-to-convert-string-i.js)|Medium|
21162116
2980|[Check if Bitwise OR Has Trailing Zeros](./solutions/2980-check-if-bitwise-or-has-trailing-zeros.js)|Easy|
21172117
2981|[Find Longest Special Substring That Occurs Thrice I](./solutions/2981-find-longest-special-substring-that-occurs-thrice-i.js)|Medium|
2118+
2997|[Minimum Number of Operations to Make Array XOR Equal to K](./solutions/2997-minimum-number-of-operations-to-make-array-xor-equal-to-k.js)|Medium|
21182119
2999|[Count the Number of Powerful Integers](./solutions/2999-count-the-number-of-powerful-integers.js)|Hard|
21192120
3024|[Type of Triangle](./solutions/3024-type-of-triangle.js)|Easy|
21202121
3042|[Count Prefix and Suffix Pairs I](./solutions/3042-count-prefix-and-suffix-pairs-i.js)|Easy|
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* 2997. Minimum Number of Operations to Make Array XOR Equal to K
3+
* https://leetcode.com/problems/minimum-number-of-operations-to-make-array-xor-equal-to-k/
4+
* Difficulty: Medium
5+
*
6+
* You are given a 0-indexed integer array nums and a positive integer k.
7+
*
8+
* You can apply the following operation on the array any number of times:
9+
* - Choose any element of the array and flip a bit in its binary representation. Flipping a bit
10+
* means changing a 0 to 1 or vice versa.
11+
*
12+
* Return the minimum number of operations required to make the bitwise XOR of all elements of the
13+
* final array equal to k.
14+
*
15+
* Note that you can flip leading zero bits in the binary representation of elements. For example,
16+
* for the number (101)2 you can flip the fourth bit and obtain (1101)2.
17+
*/
18+
19+
/**
20+
* @param {number[]} nums
21+
* @param {number} k
22+
* @return {number}
23+
*/
24+
var minOperations = function(nums, k) {
25+
let xorResult = 0;
26+
for (const num of nums) {
27+
xorResult ^= num;
28+
}
29+
30+
let result = 0;
31+
let diff = xorResult ^ k;
32+
while (diff > 0) {
33+
result += diff & 1;
34+
diff >>= 1;
35+
}
36+
37+
return result;
38+
};

0 commit comments

Comments
 (0)