table of Contents
topic
1486. Array XOR operation
gives you two integers, n and start.
The array nums is defined as: nums[i] = start + 2*i (subscript starts from 0) and n == nums.length.
Please return the result of bitwise exclusive OR (XOR) of all elements in nums.
Example 1:
输入:n = 5, start = 0
输出:8
解释:数组 nums 为 [0, 2, 4, 6, 8],其中 (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8 。
"^" 为按位异或 XOR 运算符。
Example 2:
输入:n = 4, start = 3
输出:8
解释:数组 nums 为 [3, 5, 7, 9],其中 (3 ^ 5 ^ 7 ^ 9) = 8.
Example 3:
输入:n = 1, start = 7
输出:7
Example 4:
输入:n = 10, start = 5
输出:2
prompt:
1 <= n <= 1000
0 <= start <= 1000
n == nums.length
Problem solution (Java)
class Solution
{
public int xorOperation(int n, int start)
{
//初始化nums数组
int[] nums = new int[n];
for(int index = 0;index < n;index++)
{
nums[index] = start + 2 * index;
}
int result = nums[0];
for(int index = 1;index < n;index++)
{
result = result^nums[index];
}
return result;
}
}