본문 바로가기
알고리즘/Codewars

[Codewars] Sum of Digits / Digital Root (6 kyu) / JavaScript

by fluss 2022. 11. 7.

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);
}

댓글