Minimum flips to make all 1 s in left and 0 s in right | Set 1 ( Using Bitmask ) | Function to count minimum number of flips ; This is converting string s into integer of base 2 ( if s = '100' then num = 4 ) ; Initialize minXor with n that can be maximum number of flips ; Right shift 1 by ( n - 1 ) bits ; Calculate bitwise XOR of num and mask ; Math . min ( a , b ) returns minimum of a and b return minimum number of flips till that digit ; Function to count number of 1 s ; Driver Code
function findMiniFlip ( nums ) { let n = nums . length ; let s = " " ; for ( let i = 0 ; i < n ; i ++ ) s += nums [ i ] ; let num = parseInt ( s , 2 ) ; let minXor = n ; let mask = ( 1 << ( n - 1 ) ) ; while ( n - 1 > 0 ) { let temp = ( num ^ mask ) ; minXor = Math . min ( minXor , countones ( temp ) ) ; n -- ; mask = ( mask | ( 1 << n - 1 ) ) ; } return minXor ; } function countones ( n ) { let c = 0 ; while ( n > 0 ) { n = n & ( n - 1 ) ; c ++ ; } return c ; } let nums = [ 1 , 0 , 1 , 1 , 0 , 0 , 0 ] ; let n = findMiniFlip ( nums ) ; document . write ( n ) ;