본문으로 바로가기

재직중인 회사에서도 채용 시 코딩테스트로 쓴다고 해서 들어 봤는데 기출 문제도 있는지 몰랐다가 우연히 알게되서 Codlility Lesson 을 통해 알고리즘 공부를 하고 있다.

하나씩 풀다보면 와, 참 이 함수를 이렇게 쓰기도 하는 구나 같은 함수 사용에 재발견도 하고-

어떻게 하면 좀 더 효율적인 코드가 되는지. 가끔 내 코딩력에 한계도 느끼는 재미(?)가 쏠쏠하다.

그리고, 문제 하나당 내 답과 찾아본 답을 기록하려고 한다.


물론, 언어는 Javascript 이다.


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.
For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: 

one of length 4 and one of length 3. 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. The number 32 has binary representation 100000 and has no binary gaps.

Write a function:
function solution(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.
For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5. Given N = 32 the function should return 0, because N has binary representation '100000' and thus no binary gaps.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [1..2,147,483,647].


해석하자면, 1041 과 같은 정수가 주어지면 2진수로 변환한다. 10000010001 인데 여기서 1과 1 사이에 0 개수가 제일 긴 값을 반환하라 이다.

예를 들어 위 같은 경우는 1과 1사이의 0 갯수가 3과 5가 있으니 5를 반환하면 된다. 100000 과 1111 일 경우는 1과 1사이가 아예 없으니 반환 값은 0이다.  1001 일 경우는 2이다.


코드는 다음과 같이 짰다.

function solution(N) {
    // 2진수로 변환
    let arr = N.toString(2).split(/(?!1)(0+)(?=1)/); // 정규식으로 1과 1사이를 찾는다.
    let arrSizes, max;

    // 1이 없는 놈만 골라낸다.
    let filteredArr = arr.filter(zeroes => zeroes.indexOf('1') === -1) || []; 

    if(filteredArr.length > 0) {
        arrSizes = filteredArr.map(binString => binString.length); // gap 계산
        max = arrSizes.reduce((a, b) => a >= b ? a : b); // 최대값 찾기
    } else {
        max = 0;
    }

    return max;
}
여태껏 공부를 하면서 toString 함수를 써본적은 많지만 parameter 에 숫자로 2를 넣어줬을 때 2진수로 변환해주는지 처음 알았다. 
그래서 블로그에 2진수 외에 다른 진수로 변환하는 방법도 겸사 겸사 찾아서 정리도 했다. 참고


다음엔 다음 문제를 풀어보고 포스팅하는 방법으로 계속 글을 올려 볼까한다. (얼마나 오래 할지는...ㅎㅎㅎ)