XOR Operation in an Array LeetCode Solution - The Coding Shala
Home >> LeetCode >> XOR Operation in an Array
Other Posts You May Like
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; } }
- LeetCode - Number of Steps to Reduce a Number to Zero
- LeetCode - Binary Number with Alternating Bits
- LeetCode - Split a String int Balanced Strings
- LeetCode - Defanging IP Address
- LeetCode - Number of Good Pairs
Comments
Post a Comment