Minimum insertions to make XOR of an Array equal to half of its sum | Java program to make XOR of all array elements equal to half of its sum by minimum insertions ; Function to make XOR of the array equal to half of its sum ; Calculate the sum and Xor of all the elements ; If the required condition satisfies already , return the original array ; If Xor is already zero , Insert sum ; Otherwise , insert xr and insert sum + xr ; Driver code
import java . util . * ; class GFG { static int make_xor_half ( ArrayList < Integer > arr ) { int sum = 0 , xr = 0 ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { int a = arr . get ( i ) ; sum += a ; xr ^= a ; } if ( 2 * xr == sum ) return - 1 ; if ( xr == 0 ) { arr . add ( sum ) ; return 1 ; } arr . add ( xr ) ; arr . add ( sum + xr ) ; return 2 ; } public static void main ( String [ ] args ) { int N = 7 ; ArrayList < Integer > nums = new ArrayList < Integer > ( Arrays . asList ( 3 , 4 , 7 , 1 , 2 , 5 , 6 ) ) ; int count = make_xor_half ( nums ) ; if ( count == - 1 ) System . out . print ( - 1 + "NEW_LINE"); else if ( count == 1 ) System . out . print ( nums . get ( N ) + "NEW_LINE"); else System . out . print ( nums . get ( N ) + " ▁ " + nums . get ( N + 1 ) + "NEW_LINE"); } }