Find number of subarrays with XOR value a power of 2 | C # Program to count number of subarrays with Bitwise - XOR as power of 2 ; Function to find number of subarrays ; Hash Map to store prefix XOR values ; When no element is selected ; Check for all the powers of 2 , till a MAX value ; Insert Current prefixxor in Hash Map ; Driver Code
using System ; using System . Collections . Generic ; class GFG { static int MAX = 10 ; static int findSubarray ( int [ ] array , int n ) { Dictionary < int , int > mp = new Dictionary < int , int > ( ) ; mp . Add ( 0 , 1 ) ; int answer = 0 ; int preXor = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int value = 1 ; preXor ^= array [ i ] ; for ( int j = 1 ; j <= MAX ; j ++ ) { int Y = value ^ preXor ; if ( mp . ContainsKey ( Y ) ) { answer += mp [ Y ] ; } value *= 2 ; } if ( mp . ContainsKey ( preXor ) ) { mp [ preXor ] = mp [ preXor ] + 1 ; } else { mp . Add ( preXor , 1 ) ; } } return answer ; } public static void Main ( String [ ] args ) { int [ ] array = { 2 , 6 , 7 , 5 , 8 } ; int n = array . Length ; Console . WriteLine ( findSubarray ( array , n ) ) ; } }