[codewars] Sum of Digits / Digital Root

KJA·2022년 8월 30일
0

https://www.codewars.com/kata/541c8630095125aba6000c00


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.

Example

    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

문제 해결

function digitalRoot(n) {
    if(n < 10) return n;
    return digitalRoot(n.toString().split('').reduce((acc, cur) => acc + parseInt(cur), 0));
}

다른 풀이

function digital_root(n) {
  return (n - 1) % 9 + 1;
}
  • parseInt() 말고 + 사용
function digital_root(n) {
  if (n < 10) return n;
  
  return digital_root(
    n.toString().split('').reduce(function(acc, d) { return acc + +d; }, 0));
}

0개의 댓글