요약
풀이 시간 : 19분 21초
1. 문제 순서대로 처리하면됨
2. while 문으로 처리하면되는거아닌가?, 재귀에 대해서 공부 필요
문제 링크
[프로그래머스] 이진 변환 반복하기
풀이
function solution(s) {
let currentS = s;
let zeroCount = 0;
let steps = 0;
while (currentS.length !== 1) {
const filteredArray = [...currentS].filter(str => str !== "0");
zeroCount += currentS.length - filteredArray.length;
currentS = filteredArray.length.toString(2);
steps++;
}
return [steps, zeroCount];
}
재귀 적용해서 리팩토링
function solution(s) {
const process = (currentS, steps = 0 ,zeroCount = 0) => {
if(currentS.length === 1) return [steps, zeroCount];
const filteredArray = [...currentS].filter(s => s !== "0");
zeroCount += currentS.length - filteredArray.length;
const nextS = filteredArray.length.toString(2);
return process(nextS, steps + 1, zeroCount);
}
return process(s);
}