Last active
May 6, 2017 16:52
-
-
Save ekarudianto/c10f4f7d8e319b08c5a5c608ac45c7e3 to your computer and use it in GitHub Desktop.
Codility lesson - Binnary Gap (java)
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
public class Main { | |
private String BINARY_SPLITTER = "1"; | |
public static int binaryGap(int N) { | |
String binary = Integer.toBinaryString(N); | |
if (binary.indexOf(BINARY_SPLITTER) != -1) { | |
String[] gap = binary.split(BINARY_SPLITTER); | |
int maxLength = 0; | |
for (int i = 0; i < gap.length; i++) { | |
if (gap[i].length() > maxLength) { | |
maxLength = gap[i].length(); | |
} | |
} | |
return maxLength; | |
} | |
return 0; | |
} | |
public static void main(String[] args) { | |
// Binnary gap is 5 because 1041 converted to binary is | |
// 10000010001 which has the first gap of 5 length and 3 length | |
// The longest is 5 | |
System.out.println("Binary gap " + binaryGap(1041)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment