Construct the smallest possible Array with given Sum and XOR | C ++ program for the above approach ; Function to find array ; array not possible ; Array possible with exactly 1 or no element ; Checking array with two elements possible or not . ; Driver Code ; Given sum and value of Bitwise XOR ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findArray ( int sum , int xorr ) { if ( xorr > sum sum % 2 != xorr % 2 ) { cout << " No ▁ Array ▁ Possible STRNEWLINE " ; return ; } if ( sum == xorr ) { if ( sum == 0 ) cout << " Array ▁ is ▁ empty " << " ▁ with ▁ size ▁ 0 STRNEWLINE " ; else cout << " Array ▁ size ▁ is ▁ " << 1 << " Array is " << sum << " STRNEWLINE " ; return ; } int mid = ( sum - xorr ) / 2 ; if ( xorr & mid == 1 ) { cout << " Array ▁ size ▁ is ▁ " << 3 << " STRNEWLINE " ; cout << " Array ▁ is ▁ " << xorr << " ▁ " << mid << " ▁ " << mid << " STRNEWLINE " ; } else { cout << " Array ▁ size ▁ is ▁ " << 2 << " STRNEWLINE " ; cout << " Array ▁ is ▁ " << ( xorr + mid ) << " ▁ " << mid << " STRNEWLINE " ; } } int main ( ) { int sum = 4 , xorr = 2 ; findArray ( sum , xorr ) ; cout << " STRNEWLINE " ; return 0 ; }