[Codility Lessons] 1. Iterations - BinaryGap

doongdoong·2020년 10월 9일
0

Codility Lessons

목록 보기
1/5

https://app.codility.com/programmers/lessons/1-iterations/binary_gap/

풀이

  • 이진으로 변환
  • 각 자릿수를 배열로 변환
  • 1을 만났을 때 open, 다음 값이 1이라면 close. (그 사에에서 count)
    • count가 이전의 count(answer) 보다 크다면 answer에 대입
    • close일 시에는 count 초기화
function solution(N) {
  let answer = 0;
  let count = 0;
  let open = false;

  const binary = N.toString(2)
    .split('')
    .map((v) => +v);
  binary.forEach((bNum, index) => {
    if (bNum === 1) {
      open = true;
      return;
    }

    if (open && bNum === 0) {
      count += 1;

      if (index + 1 < binary.length && binary[index + 1] === 1) {
        open = false;
        answer = count > answer ? count : answer;
        count = 0;
      }
    }
  });

  return answer;
}
profile
PS 연습장

0개의 댓글