fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static int cntSubarrays(int[] arr, int k) {
  11. // code here
  12. Map<Integer, Integer> freq = new HashMap<>();
  13. int count = 0;
  14. int prefixXor = 0;
  15.  
  16. for (int num : arr) {
  17. prefixXor ^= num;
  18. if (prefixXor == k) {
  19. count++;
  20. }
  21. int required = prefixXor ^ k;
  22. if (freq.containsKey(required)) {
  23. count += freq.get(required);
  24. }
  25.  
  26. freq.put(prefixXor, freq.getOrDefault(prefixXor, 0) + 1);
  27. }
  28.  
  29. return count;
  30. }
  31. public static void main(String [] args){
  32. Scanner sc=new Scanner(System.in);
  33. int n=sc.nextInt();
  34. int [] arr=new int[n];
  35. for(int i=0;i<n;i++){
  36. arr[i]=sc.nextInt();
  37. }
  38. int k=sc.nextInt();
  39. int cnt=cntSubarrays(arr,k);
  40. System.out.println("Subarrays with given XOR "+k+" is : "+cnt);
  41. sc.close();
  42. }
  43. }
Success #stdin #stdout 0.19s 60760KB
stdin
5
5 6 7 8 9
5
stdout
Subarrays with given XOR 5 is : 2