숫자를 받아서 결과가 한 자리 숫자가 아닐 때까지 계속 숫자를 더하는 함수를 작성해야 합니다. 한 자리 숫자가 있으면 반환합니다.
이에 대한 코드는 매우 간단합니다. 숫자가 9보다 크거나 -9보다 작을 때까지 숫자를 계속 추가하는 재귀 함수를 작성합니다(논리를 두 번 작성할 필요가 없도록 부호를 별도로 처리합니다)피>
예시
const sumRecursively = (n, isNegative = n < 0) => {
n = Math.abs(n);
if(n > 9){
return sumRecursively(parseInt(String(n).split("").reduce((acc,val) => {
return acc + +val;
}, 0)), isNegative);
}
return !isNegative ? n : n*-1;
};
console.log(sumRecursively(88));
console.log(sumRecursively(18));
console.log(sumRecursively(-345));
console.log(sumRecursively(6565)); 출력
콘솔의 출력은 -
7 9 -3 4