Tuesday, July 4, 2017

Binary Gap

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.

import java.util.Arrays;

public class BinaryGap {
     public static void main(String[] args) {
          BinaryGap bg = new BinaryGap();
          for (int i = 1; i < 10; i++) {
               System.out.println(bg.solution(i));
          }
     }

     public int solution(int n) {
          return Arrays.stream(Integer.toBinaryString(n).replaceAll("0+$", "").split("1")).mapToInt(String::length).max().orElse(0);
     }
}


No comments:

Post a Comment