XOR Operation in an Array LeetCode Solution - The Coding Shala

Home >> LeetCode >> XOR Operation in an Array

 In this post, we will learn how to solve LeetCode's XOR Operation in an Array Problem and will implement its solution in Java.

XOR Operation in an Array 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.

Example 1:
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 the bitwise XOR operator.

LeetCode - XOR Operation in an Array Java Solution

Approach 1

Simple Math and xor operation.

Java Program: 

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


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Time Complexity, Space Complexity, Asymptotic Notations - The Coding Shala

Graph Representation using Adjacency Matrix - The Coding Shala

LeetCode - Crawler Log Folder Solution - The Coding Shala

Java Method Overloading - The Coding Shala

Client-Server Java Program (Socket Programming) - The Coding Shala