Minimum flips to make all 1 s in left and 0 s in right | Set 1 ( Using Bitmask ) | Java program to find minimum flips to make all 1 s in left ; 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
import java . io . * ; class GFG { public static int findMiniFlip ( int [ ] nums ) { int n = nums . length ; String s = " " ; for ( int i = 0 ; i < n ; i ++ ) s += nums [ i ] ; long num = Integer . parseInt ( s , 2 ) ; int minXor = n ; long mask = ( 1 << ( n - 1 ) ) ; while ( n - 1 > 0 ) { long temp = ( num ^ mask ) ; minXor = Math . min ( minXor , countones ( temp ) ) ; n -- ; mask = ( mask | ( 1 << n - 1 ) ) ; } return minXor ; } public static int countones ( long n ) { int c = 0 ; while ( n > 0 ) { n = n & ( n - 1 ) ; c ++ ; } return c ; } public static void main ( String [ ] args ) { int [ ] nums = { 1 , 0 , 1 , 1 , 0 , 0 , 0 } ; int n = findMiniFlip ( nums ) ; System . out . println ( n ) ; } }