Skip to content

Instantly share code, notes, and snippets.

@aungtuntun
Created April 2, 2020 17:27
Show Gist options
  • Select an option

  • Save aungtuntun/99209c5718947533e010feff8dd6b599 to your computer and use it in GitHub Desktop.

Select an option

Save aungtuntun/99209c5718947533e010feff8dd6b599 to your computer and use it in GitHub Desktop.
Find longest sequence of zeros in binary representation of an integer.
package com.spring.api.eastates;
import org.testng.annotations.Test;
@Test(timeOut = 1000)
public class BinaryGap {
public static void main(String[] args) {
System.out.println(transformBinary(4848));
System.out.println(Integer.toBinaryString(4848));
System.out.println(longestZeroInBinary(4848));
}
public static String transformBinary(int number) {
if (number<= 0 ) {
throw new IllegalArgumentException("Number must be positive and greater than 0");
}
String value = "";
while (number > 0) {
value = ((number % 2) == 0? "0" : "1") + value;
number = number / 2;
}
return value;
}
// longest consecutive zeroes in the binary
public static int longestZeroInBinary(int number) {
int maxCount = -1; // max length of zero
int contunuous = 0; // current 0 count
String binaryValue = ""; // value in binary
while (number != 0) { // check number is greater than
if ((number & 1) == 0) { // check condition with bitwise operator '&', eg. (1 & 1) == 1, (10 & 1) == 0
contunuous++;
number >>=1; // moving binary position 1
binaryValue = "0" + binaryValue;
maxCount = Math.max(maxCount, contunuous);
}else {
maxCount = Math.max(maxCount, contunuous);
contunuous = 0;
number >>= 1;
binaryValue = "1" + binaryValue;
/* 0 1 2 3 4 5 6 7 8 9 10
* 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010
* 1010 => move binary position 1 to right and fill with 0 from left, 0101
*/
}
}
System.out.println(binaryValue);
return maxCount;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment