Created
October 1, 2020 06:16
-
-
Save palaniraja/d5f7c606056fff4485863138c511817c to your computer and use it in GitHub Desktop.
min. bit flip reqd
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Main | |
{ | |
public static void main(String args[]) | |
{ | |
int[] prbArray = new int[]{ 0,0,0,1,0,1,0,1,1,1 }; | |
Solution prb = new Solution(); | |
System.out.println(prb.solution(prbArray)); | |
} | |
} | |
class Solution { | |
// Utility method to flip a int bit | |
public int flip(int n) | |
{ | |
return (n == 0) ? 1 : 0; | |
} | |
// Utility method to get minimum flips when | |
// alternate string starts with expected int | |
public int getFlipWithStartingBit(int[] arr, | |
int expected) | |
{ | |
int flipCount = 0; | |
for (int i = 0; i < arr.length; i++) | |
{ | |
// if current int is not expected, | |
// increase flip count | |
if (arr[i] != expected) | |
flipCount++; | |
// flip expected int each time | |
expected = flip(expected); | |
} | |
return flipCount; | |
} | |
// method return minimum flip to make bit alternative | |
public int solution(int[] prbArr) | |
{ | |
// return minimum of following two | |
// 1) flips when alternate int[] starts with 0 | |
// 2) flips when alternate int[] starts with 1 | |
return Math.min(getFlipWithStartingBit(prbArr, 0), | |
getFlipWithStartingBit(prbArr, 1)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment