[프로그래머스 lev2/JS] 이진 변환 반복하기

woolee의 기록보관소·2022년 11월 8일
0

알고리즘 문제풀이

목록 보기
83/178

문제 출처

프로그래머스 lev2 - 이진 변환 반복하기

문제

나의 풀이

function solution(s) {
  let answer = new Array(2).fill(0);
  s=s.split('');

  while (1) {
    if (s.length === 1 && s[0] === '1') break;

    s = s.filter((el) => {
      if (el === '1') return el;
      else if (el === '0') answer[1]++;
    });
    answer[0]++;
    s = Number(s.length).toString(2).split('');
  }

  return answer;
}

console.log(solution("110010101001"));

다른 풀이

function solution(s) {
    var ans = [0,0];
    while (s !== "1"){
        const oldLen = s.length;
        s = s.replace(/0/g, "");
        const newLen = s.length;
        s = newLen.toString('2');

        ans[1] += oldLen - newLen;
        ans[0]++;
    }

    return ans;
}
profile
https://medium.com/@wooleejaan

0개의 댓글