Generate an array having sum of Bitwise OR of same | C ++ program for the above approach ; Function to print the resultant array ; Stores the sum of the array ; Calculate sum of the array ; If sum > K ; Not possible to construct the array ; Update K ; Stores the resultant array ; Traverse the array ; Stores the current element ; If jth bit is not set and value of 2 ^ j is less than K ; Update curr ; Update K ; Push curr into B ; If K is greater than 0 ; Print the vector B ; Otherwise ; Driver Code ; Input ; Size of the array ; Given input ; Function call to print the required array
#include <bits/stdc++.h> NEW_LINE using namespace std ; void constructArr ( int A [ ] , int N , int K ) { int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += A [ i ] ; } if ( sum > K ) { cout << -1 << " STRNEWLINE " ; return ; } K -= sum ; vector < int > B ; for ( int i = 0 ; i < N ; i ++ ) { int curr = A [ i ] ; for ( int j = 32 ; j >= 0 and K ; j -- ) { if ( ( curr & ( 1LL << j ) ) == 0 and ( 1LL << j ) <= K ) { curr |= ( 1LL << j ) ; K -= ( 1LL << j ) ; } } B . push_back ( curr ) ; } if ( ! K ) { for ( auto it : B ) { cout << it << " ▁ " ; } cout << " STRNEWLINE " ; } else { cout << " - 1" << " STRNEWLINE " ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 32 ; constructArr ( arr , N , K ) ; }