내가 접근한 방식은
1) 양수 N을 이진법으로 바꾸고
2) 1을 기준으로 split 해준다.
3) 배열에서 첫값과 마지막 값을 버리고
4) 나머지 중에서 길이가 제일 긴 string의 길이를 리턴한다.
const solution = N => {
const binary = N.toString(2);
const splited = binary.split("1");
const gaps = splited.slice(1,-1);
const len = gaps.map(x => x.length);
return (len.length < 1)
? 0
: Math.max(...len);
}
3)에서 끝 값들을 버리는 이유는
binary gap은 1과 1사이에 있는 0이어야 하는데
split을 해주었을때 한쪽에만 1이 있는 것도 배열에 담기기 때문이다.
ex) N=529 일때
const binary = N.toString(2);
console.log(binary); // '1000010001'
const splited = binary.split("1");
console.log(splited); // [ '', '0000', '000', '' ]
ex) N=20 일때
const binary = N.toString(2);
console.log(binary); // '10100'
const splited = binary.split("1");
console.log(splited); // [ '', '0', '00' ]