A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N. E.g.: 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. Write a function: class Solution { public int binary_gap(int N); } that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap.

Respuesta :

This is the best way:

class Solution {    public static int solution(int N) {        return Optional.ofNullable(N)        .map(Integer::toBinaryString)        .filter(n -> n.length() > 1)        .map(t -> {            List<Integer> counts = new ArrayList<>();            int count = 0;            for(int i = 0; i < t.length(); i++)            {                if(t.charAt(i) == '0') {                    count += 1;                } else if(count > 0) {                    counts.add(count);                    count = 0;                }            }            if(counts.size() > 0) {                Collections.sort(counts);                return counts.get(counts.size() - 1);            }            return 0;        })        .orElse(0);    }}