Codility - BinaryGap

Codility - BinaryGap


Codility Task:
BinaryGap

Problem Definition:
Find the longest sequence of zeros in binary representation of an integer.

Solution:
public int solution(int N) {
String binary = Integer.toBinaryString(N);
int i = binary.length() - 1;
while(binary.charAt(i) == '0') {
i--;
}
int binaryGap = 0;
int tempBinaryGap = 0;
for(; i >= 0; i--) {
if (binary.charAt(i) == '1') {
binaryGap = Math.max(binaryGap, tempBinaryGap);
tempBinaryGap = 0;
} else {
tempBinaryGap++;
}
}
return binaryGap;
}
view raw .java hosted with ❤ by GitHub

0 comments:

Post a Comment