XOR operation in an array
December 27, 2022
bit-manipulationProblem URL: XOR operation in an array
We will generate the array and then XOR all the elements.
class Solution:
def xorOperation(self, n: int, start: int) -> int:
res = 0
for i in range(n):
num = start + 2*i
res ^= num
return res
Time complexity: O(n)
Space complexity: O(1)
We can also use reduce
function to XOR all the elements.
class Solution:
def xorOperation(self, n: int, start: int) -> int:
return reduce(lambda x, y: x ^ y, [start + 2*i for i in range(n)])