I'm currently working on solving the binary gap problem (counting the number of 0's between two 1's, and returning the largest gap of 0's found), my solution first starts off with converting the integer N into a string of N's binary form, which works fine.
Conceptually what I'm doing (or at least think I'm doing) was counting the 0's until I reach a 1 character, which is then compared to the current count of 0's under the variable gap, I then would zero out my zero counter zero_count, and I also added an if statement to check for the case of it reaching the end of the binary string, returning 0 if no and 1 if found.
For some reason I'm getting an infinite loop, and I think I've narrowed it down to the index value not incrementing, and I'm not sure why. If someone could explain I would greatly appreciate it!
This was done in Java.
import java.util.*;
class Solution {
public int solution(int N) {
// write your code in Java SE 8
String binary = "";
int power = 31;
//double expo = Math.pow(2,power);
while(power !=-1){
if(N - Math.pow(2,power) > -1){
binary += "1";
N -= Math.pow(2,power);
}
else{binary += "0";}
power--;
}
System.out.println(binary);
//above works
int gap = 0;
int zero_count = 0;
int index = 0;
for( int i = 0; i < binary.length(); i++){
if(binary.charAt(i) == '1'){
index= i+1;
while(binary.charAt(index) =='0'){
index++;
zero_count++;
if(index == binary.length()-1){
return 0;
}
}
}
if(zero_count > gap){
gap = zero_count;
zero_count = 0;
}
i = index;
}
return gap;
}
}