LeetCode in Kotlin

2997. Minimum Number of Operations to Make Array XOR Equal to K

Medium

You are given a 0-indexed integer array nums and a positive integer k.

You can apply the following operation on the array any number of times:

Return the minimum number of operations required to make the bitwise XOR of all elements of the final array equal to k.

Note that you can flip leading zero bits in the binary representation of elements. For example, for the number (101)2 you can flip the fourth bit and obtain (1101)2.

Example 1:

Input: nums = [2,1,3,4], k = 1

Output: 2

Explanation: We can do the following operations:

The XOR of elements of the final array is (6 XOR 1 XOR 2 XOR 4) == 1 == k.

It can be shown that we cannot make the XOR equal to k in less than 2 operations.

Example 2:

Input: nums = [2,0,2,0], k = 0

Output: 0

Explanation: The XOR of elements of the array is (2 XOR 0 XOR 2 XOR 0) == 0 == k. So no operation is needed.

Constraints:

Solution

@Suppress("NAME_SHADOWING")
class Solution {
    fun minOperations(nums: IntArray, k: Int): Int {
        var k = k
        var count = 0
        var xor = 0
        for (num in nums) {
            xor = xor xor num
        }
        while (xor > 0 || k > 0) {
            if (xor % 2 != k % 2) {
                count++
            }
            xor /= 2
            k /= 2
        }
        return count
    }
}