Minimize K whose XOR with given array elements leaves array unchanged | C ++ program for the above approach ; Function to find the minimum value of K in given range ; Declare a set ; Initialize count variable ; Iterate in range [ 1 , 1024 ] ; counter set as 0 ; Iterating through the Set ; Check if the XOR calculated is present in the Set ; If the value of Bitwise XOR inside the given set then increment count ; Check if the value of count is equal to the size of set ; Return minimum value of K ; If no such K is found ; Driver Code ; Given array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int min_value ( int arr [ ] , int N ) { int x , X , K ; set < int > S ; for ( int i = 0 ; i < N ; i ++ ) { S . insert ( arr [ i ] ) ; } int count = 0 ; for ( int i = 1 ; i <= 1024 ; i ++ ) { count = 0 ; for ( auto it = S . begin ( ) ; it != S . end ( ) ; it ++ ) { X = ( ( i * it ) - ( i & * it ) ) ; if ( S . find ( X ) != S . end ( ) ) { count ++ ; } } if ( count == S . size ( ) ) { K = i ; return K ; } } return -1 ; } int main ( ) { int arr [ ] = { 1 , 0 , 3 , 3 , 0 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << min_value ( arr , N ) ; return 0 ; }