Persistent Bugger. ( 6 kyu )
문제
Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.
For example:
persistence(39) === 3 // because 3*9 = 27, 2*7 = 14, 1*4=4
// and 4 has only one digit
persistence(999) === 4 // because 9*9*9 = 729, 7*2*9 = 126,
// 1*2*6 = 12, and finally 1*2 = 2
persistence(4) === 0 // because 4 is already a one-digit number
한자리수가 될 때까지 각 자릿수를 곱하는 문제
풀이
let count = 0;
function persistence(num) {
if ( num.toString().length === 1 ) {
let result = count;
count = 0;
return result;
} else {
count++;
return persistence(num.toString().split('').reduce((a,b) => { return parseInt(a)*parseInt(b) }))
}
}
재귀로 한번 돌때마다 카운트를 1씩 올려주다가 길이가 한글자가 되면 결과값을 리턴해주는 방법.
마지막에 굳이 result 변수로 값을 복사해서 count를 초기화 한 이유는 count 변수 선언을 함수 밖에해서 테스트코드가 돌아갈 때 계속 count가 누적되는 문제가 있어 해결한 것.
다른 사람의 풀이
const persistence = num => {
return `${num}`.length > 1
? 1 + persistence(`${num}`.split('').reduce((a, b) => a * +b))
: 0;
}
가장 좋아요를 많이 받은 코드는 아니지만 딱봐도 간단하고 명료해 맘에든 코드!