Skip to content

Latest commit

 

History

History
54 lines (39 loc) · 1.6 KB

1486.md

File metadata and controls

54 lines (39 loc) · 1.6 KB

Given two non-negative integers n and start, construct an array nums of length n as such that nums[i] = start + 2*i. Create an output variable of initial value 0. For each number x within the array nums, update the value of the output variable as such that it equals the xor of its current value and the number x.

class Solution:
    def xorOperation(self, n: int, start: int) -> int:
        
        nums = []
        for i in range(n):
            nums.append(start + 2*i)
            
        output = 0
        for num in nums:
            output = output ^ num
            
        return output

This can be rewritten to employ Python list comprehension and the reduce function:

from functools import reduce

class Solution:
    def xorOperation(self, n: int, start: int) -> int:
        return reduce(lambda a, b: a ^ b, [start + 2*i for i in range(n)])

Alternatively, given that the xor function is both commutative and associative, there is no need to generate the array nums before computing the xor of its constituent values - as such, the code can be rewritten as follows:

class Solution:
    def xorOperation(self, n: int, start: int) -> int:
        output = 0
        
        for i in range(n):
            output = output ^ (start + 2*i)
            
        return output

This can be further rewritten to employ a while loop:

class Solution:
    def xorOperation(self, n: int, start: int) -> int:
        output = 0
        
        i = 0
        while i < n:
            output = output ^ (start + 2*i)
            i += 1
            
        return output