I want to know the performance of my code for following problem description.
For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps.
public static int getBinaryGap(int N) {
if (N < 5) {
return 0;
}
String binaryRep = Integer.toBinaryString(N);
int currentGap = 0;
int finalGap = 0;
for (int i = 0; i+1 < binaryRep.length(); i++) {
if (currentGap == 0) {
if (binaryRep.charAt(i) == '1' && binaryRep.charAt(i + 1) == '0') {
currentGap++;
}
} else {
if (binaryRep.charAt(i + 1) == '0') {
currentGap++;
}
if (binaryRep.charAt(i + 1) == '1') {
finalGap = finalGap<currentGap ? currentGap:finalGap;
currentGap = 0;
}
}
}
return finalGap;
}