Find number of subarrays with XOR value a power of 2 | Java 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
import java . util . * ; class GFG { static int MAX = 10 ; static int findSubarray ( int array [ ] , int n ) { HashMap < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; mp . put ( 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 . get ( Y ) ; } value *= 2 ; } if ( mp . containsKey ( preXor ) ) { mp . put ( preXor , mp . get ( preXor ) + 1 ) ; } else { mp . put ( preXor , 1 ) ; } } return answer ; } public static void main ( String [ ] args ) { int array [ ] = { 2 , 6 , 7 , 5 , 8 } ; int n = array . length ; System . out . println ( findSubarray ( array , n ) ) ; } }