Codility

Binary Gap

import java.util.regex.Pattern;  
import java.util.regex.Matcher; 
import java.util.Collections;
import java.util.ArrayList;
import java.util.NoSuchElementException;

class Solution {
    public int solution(int N) {
        String bin = Integer.toBinaryString(N);
        Pattern p = Pattern.compile("(1)(0+)(?=1)");
        Matcher m = p.matcher(bin);
        ArrayList<Integer> lst= new ArrayList<Integer>();
        while(m.find()){
            lst.add(m.group(2).length());
        }
        try{
            return Collections.max(lst);
        }catch(NoSuchElementException e){
            return 0;
        }
    }
}

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 )

Google photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s