其他分享
首页 > 其他分享> > 1486. 数组异或操作

1486. 数组异或操作

作者:互联网

题目描述

 给你两个整数,n 和 start 。
 数组 nums 定义为:nums[i] = start + 2*i(下标从 0 开始)且 n == nums.length 。
 请返回 nums 中所有元素按位异或(XOR)后得到的结果。


原题请参考链接https://leetcode-cn.com/problems/xor-operation-in-an-array/

题解

方法一 【暴力破解】

class Solution:
      def xorOperation(self, n: int, start: int) -> int:
            return reduce(lambda a, b: a ^ b, map(lambda i: start + (i << 1), range(n)))

方法二 【递归】

// 因为当n==2时,n=1的情况已经被计算;n==1时需要返回的时n=0的情况,所以边界条件为n==1
class Solution:
      def xorOperation(self, n: int, start: int) -> int:
            if n == 1:
                  return start
            return self.xorOperation(n-1,start) ^ (start + 2 * (n-1))

标签:return,nums,int,self,xorOperation,start,异或,1486,数组
来源: https://www.cnblogs.com/bladers/p/14263892.html