Change bits to make specific OR value | C ++ program to change least bits to get desired OR value ; Returns max of three numbers ; Returns count of bits in N ; Returns bit at ' pos ' position ; Utility method to toggle bit at ' pos ' position ; method returns minimum number of bit flip to get T as OR value of A and B ; Loop over maximum number of bits among A , B and T ; T 's bit is set, try to toggle bit  of B, if not already ; if A 's bit is set, flip that ; if B 's bit is set, flip that ; if K is less than 0 then we can make A | B == T ; Loop over bits one more time to minimise A further ; If both bit are set , then Unset A 's bit to minimise it ; If A ' s ▁ bit ▁ is ▁ 1 ▁ and ▁ B ' s bit is 0 , toggle both ; Output changed value of A and B ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int max ( int a , int b , int c ) { return max ( a , max ( b , c ) ) ; } int bitCount ( int N ) { int cnt = 0 ; while ( N ) { cnt ++ ; N >>= 1 ; } return cnt ; } bool at_position ( int num , int pos ) { bool bit = num & ( 1 << pos ) ; return bit ; } void toggle ( int & num , int pos ) { num ^= ( 1 << pos ) ; } void minChangeToReachTaregetOR ( int A , int B , int K , int T ) { int maxlen = max ( bitCount ( A ) , bitCount ( B ) , bitCount ( T ) ) ; for ( int i = maxlen - 1 ; i >= 0 ; i -- ) { bool bitA = at_position ( A , i ) ; bool bitB = at_position ( B , i ) ; bool bitT = at_position ( T , i ) ; if ( bitT ) { if ( ! bitA && ! bitB ) { toggle ( B , i ) ; K -- ; } } else { if ( bitA ) { toggle ( A , i ) ; K -- ; } if ( bitB ) { toggle ( B , i ) ; K -- ; } } } if ( K < 0 ) { cout << " Not ▁ possible STRNEWLINE " ; return ; } for ( int i = maxlen - 1 ; K > 0 && i >= 0 ; -- i ) { bool bitA = at_position ( A , i ) ; bool bitB = at_position ( B , i ) ; bool bitT = at_position ( T , i ) ; if ( bitT ) { if ( bitA && bitB ) { toggle ( A , i ) ; K -- ; } } if ( bitA && ! bitB && K >= 2 ) { toggle ( A , i ) ; toggle ( B , i ) ; K -= 2 ; } } cout << A << " ▁ " << B << endl ; } int main ( ) { int A = 175 , B = 66 , K = 5 , T = 100 ; minChangeToReachTaregetOR ( A , B , K , T ) ; return 0 ; }