[Algorithms] – Codility Training – BinaryGap

Below is my solution for :

https://codility.com/demo/take-sample-test/binary_gap/

public static void main(String[] args) {
    System.out.println(solution(328));
}

public static int solution(int N) {
    String number = Integer.toBinaryString(N);
    Integer result = 0;
    while ( number.contains("0") && number.length() > 1){
        int firstZero = number.indexOf("0");
        number = number.substring(firstZero);
        int counter = 0;
        while (number.length()>1 && getNextValue(number).equals("0")) {
            number = number.substring(1);
            counter +=1;
        }
        if ( number.length() == 1 && number.equals("0")) {
            counter=0;
        }
        if ( result < counter){
            result = counter;
        }
    }
    return result;
}


private static String getNextValue(String value){
    return value.substring(0,1);
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s