Skip to content

Instantly share code, notes, and snippets.

@cipri7329
Created July 28, 2016 11:44
Show Gist options
  • Save cipri7329/30b956a3af700ea26f5b55c3898052ea to your computer and use it in GitHub Desktop.
Save cipri7329/30b956a3af700ea26f5b55c3898052ea to your computer and use it in GitHub Desktop.
Find longest sequence of zeros in binary representation of an integer.
/**
*
Find longest sequence of zeros in binary representation of an integer.
*/
public class BinaryLongestZeroSequence {
/**
* worst-case time complexity is O(log(N));
* number of bits = log(N) ==> worst case is O(N)
* @param N
* @return
*/
public int solution(int N) {
// write your code in Java SE 8
// System.out.println("input: " + N);
String binaryString = Integer.toBinaryString(N);
char[] binaries = binaryString.toCharArray();
boolean startedSequence = false;
int currentLength = -1;
int maxLength = 0;
for(char bit : binaries){
// System.out.print(bit + " ");
if(bit == '0') {
if(startedSequence){
currentLength ++;
}
}
else if(bit == '1') {
if(startedSequence == false) {
startedSequence = true;
}
else{
if(maxLength < currentLength){
maxLength = currentLength;
}
}
currentLength = 0;
}
}
// System.out.println("Length for "+ N + " is " + maxLength);
return maxLength;
}
public static void main (String[] args){
BinaryLongestZeroSequence algo = new BinaryLongestZeroSequence();
validate(algo, 1041, 5);
validate(algo, 8, 0);
validate(algo, 529, 4);
validate(algo, 20, 1);
validate(algo, 15, 0);
validate(algo, 9, 2);
}
private static void validate(BinaryLongestZeroSequence algo, int N, int sequenceLength){
System.out.println("==========");
if( sequenceLength == algo.solution(N))
System.out.println("PASS " + N);
else
System.out.println("FAIL " + N);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment