In this HackerRank Sansa and XOR problem solution, we have an array and we need to find the value obtained by XOR using the contiguous subarrays, followed by XOR using the values thus obtained.
Problem solution in Python.
T = int(input()) for _ in range(T): N = int(input()) ar = [int(i) for i in input().split()] result = 0 count = 0 for i in range(N): count += N - 2*i if (count) % 2 == 1: result = result ^ ar[i] print(result)
Problem solution in Java.
import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) { /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ Scanner scan = new Scanner(System.in); int numOfTests = scan.nextInt(); for(int test = 0; test < numOfTests; test++){ int[] array = new int[scan.nextInt()]; for(int i = 0; i < array.length; i++){ array[i] = scan.nextInt(); } int result = 0; if(array.length == 0) result = 0; else if(array.length == 1) result = array[0]; else if(array.length%2 == 0) result = 0; else{ for(int i = 0; i < array.length; i+=2) result^= array[i]; } System.out.println(result); } } }
Problem solution in C++.
#include <vector> #include <iterator> #include <list> #include <map> #include <math.h> #include <cmath> #include <set> #include <queue> #include <deque> #include <string> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <string.h> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cstdlib> #include <ctime> using namespace std; int main() { int t; cin>>t; while(t--) { int n,ans=0; cin>>n; for(int f=0;f<n;f++) { int x; cin>>x; if(f%2==0) ans^=x; } if(n%2) cout<<ans<<endl; else cout<<0<<endl; } }
Problem solution in C.
#include <stdio.h> #include <stdlib.h> int a[100000]; int main(){ int T,N,ans,i; scanf("%d",&T); while(T--){ ans=0; scanf("%d",&N); for(i=0;i<N;i++) scanf("%d",a+i); if(N%2){ for(i=0;i<N;i+=2) ans^=a[i]; printf("%dn",ans); } else printf("0n"); } return 0; }