题目地址:
https://leetcode.com/problems/xor-operation-in-an-array/description/
给定一个正整数 n n n和一个数 x x x,求 x ∧ ( x + 2 ) ∧ ( x + 4 ) ∧ . . . ∧ ( x + 2 n − 2 ) x\wedge (x+2)\wedge (x+4)\wedge ...\wedge (x+2n-2) x∧(x+2)∧(x+4)∧...∧(x+2n−2)。
代码如下:
class Solution {
public:
int xorOperation(int n, int start) {
int res = 0;
while (n--) res ^= start, start += 2;
return res;
}
};
时间复杂度 O ( n ) O(n) O(n),空间 O ( 1 ) O(1) O(1)。