1486.数组异或操作
题目描述
给你两个整数,n
和start
。
数组nums
定义为:nums[i] = start + 2*i
(下标从 0 开始)且 n == nums.length
。
请返回nums
中所有元素按位异或(XOR)后得到的结果。
示例1
输入:n = 5, start = 0
输出:8
解释:数组 nums 为 [0, 2, 4, 6, 8],其中 (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8 。
“^” 为按位异或 XOR 运算符。
示例2
输入:n = 4, start = 3
输出:8
解释:数组 nums 为 [3, 5, 7, 9],其中 (3 ^ 5 ^ 7 ^ 9) = 8.
示例3
输入:n = 1, start = 7
输出:7
示例4
输入:n = 10, start = 5
输出:2
提示
1 <= n <= 1000
0 <= start <= 1000
n == nums.length
模拟这个过程,创建一个数组nums并返回它的所有元素的按位异或。
代码演示
Java 模拟数组
import java.util.stream.IntStream;
public class OneQuestionPerDay1486 {
public static void main(String[] args) {
Solution s = new Solution();
System.out.println(s.xorOperation(5,0));
System.out.println(s.xorOperation(4,3));
Solution1486_02 s2 = new Solution1486_02();
System.out.println(s2.xorOperation(1,7));
System.out.println(s2.xorOperation(10,5));
}
}
class Solution {
public int xorOperation(int n, int start) {
int xor = start;
for (int i = 1; i < n; i++) {
int x = start + 2 * i;
xor = xor ^ x;
}
return xor;
}
}
class Solution1486_02 {
public int xorOperation(int n, int start) {
// IntStream 是一个原始整数值序列 lambda表达式map链式编程
return IntStream.range(0, n).boxed().map(i -> (2 * i + start)).reduce(0, (o1, o2) -> o1 ^= o2);
}
}
Java Solution 提交结果
执行用时:0 ms, 在所有 Java 提交中击败了100.00% 的用户
内存消耗:34.9 MB, 在所有 Java 提交中击败了97.92% 的用户
Java Solution_2 提交结果
执行用时:4 ms, 在所有 Java 提交中击败了100.00% 的用户
内存消耗:35.4 MB, 在所有 Java 提交中击败了10.57% 的用户
代码演示
C++ 数学方法总结公式
#include <bits/stdc++.h>
using namespace std;
/* 数学方法
sumXOR{
x x = 4 * k
1 x = 4 * k + 1
x + 1 x = 4 * k + 2
0 x = 4 * k + 3
}
result = (sumXOR(S - 1) ⊕ (sumXOR(S + n - 1)) * 2 + E)
*/
class Solution {
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;
}
int xorOperation(int n, int start) {
int S = start >> 1;
int E = n & start & 1;
int result = sumXor(S - 1) ^ sumXor(S + n - 1);
return result << 1 | E;
}
};
int main()
{
Solution s;
cout << s.xorOperation(5,0) << endl;
cout << s.xorOperation(4,3) << endl;
cout << s.xorOperation(1,7) << endl;
cout << s.xorOperation(10,5) << endl;
return 0;
}
C++ 提交结果
执行用时:0 ms, 在所有 C++ 提交中击败了100.00% 的用户
内存消耗:5.7 MB, 在所有 C++ 提交中击败了96.03% 的用户