[프로그래머스 Level 2] 이진 변환 반복하기 javascript

IT공부중·2021년 1월 4일
0

알고리즘

목록 보기
44/49

https://programmers.co.kr/learn/courses/30/lessons/70129

이진 수를 받아서 모든 0을 제거하고, 남은 길이를 다시 2진법으로 변환한 후, 1이 될때까지 계속 반복하면 되는 문제다.

function solution(s) {
    let zeroCount = 0;
    let loopCount = 0;
    
    while(s !== '1') {
        const tempLength = [...s].reduce((total, string) => {
            if(string === '0') {
              zeroCount += 1;
              return total;
            }
            return total + 1;
        }, 0);
        
        s = tempLength.toString(2);
        loopCount += 1;
    }
    
    return [loopCount, zeroCount];
}

reduce를 사용해서 0일 경우 zeroCount를 더하고, 1일 경우에만 길이를 센다. 그 길이를 2진법으로 바꾸고 한번 while문 마다 loopCount를 증가시켜 주었다.

profile
3년차 프론트엔드 개발자 문건우입니다.

0개의 댓글