https://www.codewars.com/kata/541c8630095125aba6000c00
Codewars - Achieve mastery through coding practice and developer mentorship
A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!
www.codewars.com
DESCRIPTION:
Digital root is the recursive sum of all the digits in a number.
Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. The input will be a non-negative integer.
Examples
16 --> 1 + 6 = 7
942 --> 9 + 4 + 2 = 15 --> 1 + 5 = 6
132189 --> 1 + 3 + 2 + 1 + 8 + 9 = 24 --> 2 + 4 = 6
493193 --> 4 + 9 + 3 + 1 + 9 + 3 = 29 --> 2 + 9 = 11 --> 1 + 1 = 2
설명:
자릿수근은 모든 자릿수를 재귀적으로 합한 것입니다.
n이 주어지면 n의 자릿수 합을 취합니다. 만약 값이 두 자리 이상인 경우 이 방법으로 한자리 숫자가 될 때까지 계속해서 줄이세요. 입력은 음수가 아닌 정수입니다.
예시
16 --> 1 + 6 = 7
942 --> 9 + 4 + 2 = 15 --> 1 + 5 = 6
132189 --> 1 + 3 + 2 + 1 + 8 + 9 = 24 --> 2 + 4 = 6
493193 --> 4 + 9 + 3 + 1 + 9 + 3 = 29 --> 2 + 9 = 11 --> 1 + 1 = 2
풀이
n의 길이가 1이 아닐 때까지 숫자를 하나씩 잘라서 계속 더해준다.
코드
function digitalRoot(n) {
while(n.length !== 1){
n = n.toString().split('').map(el => parseInt(el)).reduce((acc, cur) => acc + cur, 0).toString();
}
return parseInt(n);
}
'알고리즘 > Codewars' 카테고리의 다른 글
[Codewars] Get the Middle Character (7 kyu) / JavaScript (0) | 2022.11.09 |
---|---|
[Codewars] Create Phone Number (6 kyu) / JavaScript (0) | 2022.11.08 |
[Codewars] Stop gninnipS My sdroW! (6 kyu) / JavaScript (0) | 2022.11.05 |
[Codewars] If you can't sleep, just count sheep!! (8 kyu) / JavaScript (0) | 2022.11.04 |
[Codewars] Calculate average (8 kyu) / JavaScript (0) | 2022.11.03 |
댓글