LeetCode 1486: XOR Operation in an Array

Problem Description

Explanation

To solve this problem, we can create an array nums by generating each element using the formula start + 2*i, where i ranges from 0 to n-1. Then we can calculate the bitwise XOR of all elements in the array nums to get the final result.

  1. Initialize a variable result to 0.
  2. Iterate from 0 to n-1, calculate each element using the formula start + 2*i, and XOR it with the current result.
  3. Return the final result.

Time Complexity

The time complexity of this solution is O(n) where n is the given integer.

Space Complexity

The space complexity of this solution is O(1) as we are not using any extra space that grows with the input size.

Solutions

class Solution {
    public int xorOperation(int n, int start) {
        int result = 0;
        for (int i = 0; i < n; i++) {
            result ^= start + 2*i;
        }
        return result;
    }
}

Loading editor...