Category : Easy

**Problem**

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`

.

https://leetcode.com/problems/xor-operation-in-an-array/

**Examples**

**Example 1:**

1 2 3 4 | 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. Where "^" corresponds to bitwise XOR operator. |

**Example 2**:

1 2 3 | Input: n = 4, start = 3 Output: 8 Explanation: Array nums is equal to [3, 5, 7, 9] where (3 ^ 5 ^ 7 ^ 9) = 8. |

**Example 3:**

1 2 | Input: n = 1, start = 7 Output: 7 |

**Example 4:**

1 2 | Input: n = 10, start = 5 Output: 2 |

**Constraints**

`1 <= n <= 1000`

`0 <= start <= 1000`

`n == nums.length`

**Solution Approach**

In this problem, we just need to perform XOR operation on a set of elements but the elements we need to find ourselves. The calculation of elements is straightforward and it will start from the value in start variable and it increases by 2 with every step.

Coming to the solution of the problem we initialise our answer variable with the value of start. We are initialising with start and not 0 or 1 because the initial value may change the answer and give the error in the result. Then we loop through the numbers starting with 1 to n (given in the problem). We ran the loop starting from 1 because we already initialised answer variable with start hence we have used up 0th index.

We perform XOR operation using ‘^’ on all the elements and store it in the answer variable. In the end, we return the value of the same answer variable’s value as the answer.

**Solution code**

1 2 3 4 5 6 7 8 9 | class Solution { public int xorOperation(int n, int start) { int answer = start; for(int i=1; i<n; i++){ answer = answer ^ (start+ 2*i); } return answer; } } |

For more Leetcode explained solutions visit Leetcode Solutions. If you like capture the flag challenges visit here.

Check out my socials below in the footer. Feel free to ask any doubts in the comment section or contact me via Contact page I will surely respond. Happy Leetcoding