题目:
异或运算:
相同为0,不同为1
即:
0 ^ 0 = 0 ,
0 ^ 1 = 1,
1 ^ 0 = 1 ,
1 ^ 1 = 0 ,
直接解法:
java
class Solution {
public int xorOperation(int n, int start) {
int result = 0;
for(int i = 0;i<n;i++)
{
int num = start + 2*i;
result ^=num;
}
return result;
}
}
降低时间复杂度
java
class Solution {
public int xorOperation(int n, int start) {
int s = start >> 1, e = n & start & 1;
int ret = sumXor(s - 1) ^ sumXor(s + n - 1);
return ret << 1 | e;
}
public int sumXor(int x) {
if (x % 4 == 0) {
return x;
}
if (x % 4 == 1) {
return 1;
}
if (x % 4 == 2) {
return x + 1;
}
return 0;
}
}
作者:力扣官方题解
链接:https://leetcode.cn/problems/xor-operation-in-an-array/solutions/371258/shu-zu-yi-huo-cao-zuo-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。