Given an integer
Define an array
Find the bitwise XOR of all elements of nums
n
and an integer start
.Define an array
nums
where nums[i] = start + 2*i
(0-indexed) and n == nums.length
.Find the bitwise XOR of all elements of nums
Example:
Input: n=5,start=0
Output: 8 //0^2^4^6^8=8
Approach
Java
public class XOROperation {public static void main(String[] args) {int n = 5, start = 0;// array 0,2,4,6,8System.out.println(xorOperation(n, start));}private static int xorOperation(int n, int start) {if (n == 0)return 0;int nums[] = new int[n];for (int i = 0; i < n; i++) {nums[i] = start + 2 * i;}int res = nums[0];for (int i = 1; i < n; i++)res = res ^ nums[i];return res;}}
C++
#include <bits/stdc++.h>using namespace std;int xorOperation(int n, int start){if(n==0)return 0;int nums[n];for(int i=0;i<n;i++){nums[i]=start+2*i;}int res=nums[0];for(int i=1;i<n;i++)res=res^nums[i];return res;}int main(){int n=5,start=0;//array 0,2,4,6,8cout<<xorOperation(n,start);return 0;}
No comments:
Post a Comment