From d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa Mon Sep 17 00:00:00 2001 From: jack <0x6A73@pm.me> Date: Fri, 14 Jun 2024 13:13:15 -0600 Subject: initial --- min_num_opp_arr_equal_xor.py | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 min_num_opp_arr_equal_xor.py (limited to 'min_num_opp_arr_equal_xor.py') diff --git a/min_num_opp_arr_equal_xor.py b/min_num_opp_arr_equal_xor.py new file mode 100644 index 0000000..79bd53a --- /dev/null +++ b/min_num_opp_arr_equal_xor.py @@ -0,0 +1,35 @@ +# 2997. Minimum Number of Operations to Make Array XOR Equal to K + +""" +given a 0-indexed array 'nums' and a positive integer 'k'. you can apply the +following operation on the array any number of times: choose any element of +the array and flip a bit in its binary representation. flipping a bit meops +chaning a 0 to a 1 or vice versa. return the minimum number of operations +required to make the bitwise xor of all elements in the array equal to 'k'. +note that you can flip leading zero bits in the binary representation of the +elements. for example, for the number of '101_2' you can flip the fouth bit +and obtain '1101_2' +""" + + +class Solution(object): + def minOperations(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: int + """ + cnt = k + for n in nums: + cnt ^= n + ops = 0 + while cnt: + ops += cnt & 1 + cnt >>= 1 + return ops + + +if __name__ == "__main__": + obj = Solution() + print(obj.minOperations(nums=[2, 1, 3, 4], k=1)) + print(obj.minOperations(nums=[2, 0, 2, 0], k=0)) -- cgit v1.2.3