-
[Codewars] Sum of Digits / Digital RootAlgorithm 2021. 3. 17. 17:22
www.codewars.com/kata/541c8630095125aba6000c00/train/javascript
Codewars: Achieve mastery through challenge
Codewars is where developers achieve code mastery through challenge. Train on kata in the dojo and reach your highest potential.
www.codewars.com
더보기문제
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.
예제
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풀이
- 입력받은 숫자를 각 자릿수로 배열을 만든다.
- for문을 배열의 길이만큼 사용한다.
- 각 자릿수의 숫자를 꺼내 더한 값이 9보다 큰 경우에 재귀 호출한다.
- 반복하고 10보다 작아지는 경우에 리턴
function digital_root(n) { let arr = String(n).split(''); let sum = 0; for(let i = 0; i < arr.length; i++) { sum += Number(arr[i]); } if(sum < 10) return sum; if(sum > 9) return digital_root(sum); console.log('sum', sum) }
'Algorithm' 카테고리의 다른 글
[Codewars] Array.diff (0) 2021.03.20 [프로그래머스] 소수 만들기 (0) 2021.03.18 [Codewars] Which are in? (0) 2021.03.15 [프로그래머스] 예산 (0) 2021.03.11 [프로그래머스] 최대공약수와 최소공배수 (0) 2021.03.10