Leetcode 1486. XOR Operation in an Array
You are given an integer n
and an integer start
.
Define an array nums
where nums[i] = start + 2 * i
(0-indexed) and n == nums.length
.
Return the bitwise XOR of all elements of nums
.
Example:
Input: n = 5, start = 0
Output: 8
Explanation: Array nums is equal to [0, 2, 4, 6, 8] where (0^2^4^6^8) = 8.
n
always a positive integer?
n
is always a positive integer.n
and start
?
1 <= n <= 1000
and 0 <= start <= 1000
.n
be zero?
n
is at least 1 since arrays of size 0 wouldn’t produce meaningful XOR results.The strategy is straightforward:
nums
using the formula nums[i] = start + 2 * i
.public class Solution {
public int xorOperation(int n, int start) {
int xor = 0;
for (int i = 0; i < n; i++) {
xor ^= (start + 2 * i);
}
return xor;
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.xorOperation(5, 0)); // Output: 8
System.out.println(sol.xorOperation(4, 3)); // Output: 8
System.out.println(sol.xorOperation(1, 7)); // Output: 7
System.out.println(sol.xorOperation(10, 5)); // Output: 2
}
}
O(n)
, iterating through the array of size n
once.O(1)
, the space used is constant as we only use a single integer to store the XOR result. We don’t store the nums
array explicitly.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?