1486. 数组异或操作
解法1:遍历异或
class Solution:
def xorOperation(self, n: int, start: int) -> int:
res = 0
for i in range(0,n):
res ^= start
start += 2
return res
解法2:找规律
由上图可推算出,
- 当n%4==0时,res = n 只剩一个数字
- 当n%4==1时,res = 1 剩两个数字
- 当n%4==2时,res = n+1 三个数字异或正好与第四个相容
- 当n%4==3时,res = 0 没有剩下数字
所以题目中的:
- res = (start+2 * 0)^(start+2 * 1) ^(start+2 * 2) ^ … ^(start+2 * (n-2)) ^
(start+2 * (n-1)) - res>>1 = (start/2+0) ^ (start/2+1) ^ (start/2+2) ^ … ^
(start/2+(n-2)) ^(start/2+(n-1))
所以令:
-
A = 1 ^ 2 ^ 3 ^ 4 ^ …^ (start/2-1)
-
B = 1 ^ 2 ^ 3 ^ 4 ^ …^ (start/2-1)+(start/2+0) ^ (start/2+1) ^
(start/2+2) ^ … ^ (start/2+(n-2)) ^(start/2+(n-1)) = A ^ (res>>1)
得到:
res>>1 = A ^ B
然后解决最后一位是否为1的情况,异或,只有当start为奇数并且,异或数总个数为奇数才会出现1,否则就为0
1 if n%2 == 1 & start%2 == 1 else 0
代码
class Solution:
def xorOperation(self, n: int, start: int) -> int:
def solution(n):
if n%4 == 0:
return n
elif n%4 == 1:
return 1
elif n%4 == 2:
return n+1
else:
return 0
A = solution((start>>1)-1)
B = solution((start>>1)+n-1)
return 2*(A^B) + (1 if n%2 == 1 & start%2 == 1 else 0)
简化代码
class Solution:
def xorOperation(self, n: int, start: int) -> int:
def solution(n):
if n%4 == 0:
return n
elif n%4 == 1:
return 1
elif n%4 == 2:
return n+1
else:
return 0
return (solution((start>>1) - 1) ^ solution((start>>1) + n - 1)) << 1 | (n & start & 1)