给你两个整数,n 和 start 。
数组 nums 定义为:nums[i] = start + 2*i(下标从 0 开始)且 n == nums.length 。
请返回 nums 中所有元素按位异或(XOR)后得到的结果。
输入:n = 5, start = 0
输出:8 解释:数组 nums 为 [0, 2, 4, 6, 8],其中 (0 ^ 2 ^ 4 ^
6 ^ 8) = 8 。
“^” 为按位异或 XOR 运算符。
解法一:模拟
class Solution {
public:
int xorOperation(int n, int start) {
int nums[1005] = {0};
int res = 0;
for (int i = 0; i < n; i++){
nums[i] = start + 2 * i;
res = res ^ nums[i];
}
return res;
}
};
解法二:数学
异或的公式
- x ^ x = 0;
- x ^ y = y ^ x; 交换律
- (x ^ y) ^ z = x ^ (y ^ z); 结合律
- x ^ x ^ y = y; 自反律
- 4i ^ (4i + 1) ^ (4i + 2) ^ (4i + 3) = 0;
本题中需要计算start ^ (start + 2) ^ (start + 4) ^ (start + 6) ^ … ^
(start + 2(n- 1));
注意到如果将上式除2可得start/2 ^ (start/2 + i) ^ (start/2 + 2i) ^ (start/2 + 3i) ^ … ^ (start/2 + (n- 1));
因为异或是位操作,所以将每个值右移1位再进行异或对这部分位并无影响,而原式与新式的关系也易得
原式 = 新式 << 1 | e (e为原式的最低位)
因为原式的每个数要么全为奇数要么全为偶数,所以若e为1则必有n且start为奇数
所以e = start & n & 1;
class Solution {
public:
int xorOperation(int n, int start) {
int s = start>>1;
int e = n & start & 1;
int res = SumXor(s - 1) ^ SumXor(s + n -1);
return res<<1 | e;
}
int SumXor(int x){
if (x % 4 == 0) return x;
else if (x % 4 == 1) return 1;
else if (x % 4 == 2) return x + 1;
return 0;
}
};
int res = SumXor(s - 1) ^ SumXor(s + n -1);
> 根据定理有相邻的四个数异或结果为 0 :
> 4i ⊕ (4i + 1) ⊕ (4i + 2) ⊕ (4i + 3) = 0,而我们要求
> (s^ (s+1) ^ (s+2) ^ …… ^ (s+n-1)) * 2 + e 由定理有
> x ⊕ x ⊕ y = y,即(s ^(s+1) ^ (s+2) ^ …… ^ (s+n-1)) = (1 ^ 2 ^ 3 ^ …… ^ s - 1)(1 ^ 2 ^ 3 ^…… ^ s - 1 ^ s ^ (s+1) ^ (s+2) ^ …… ^ (s+n-1));