[Codewars/JS] Convert string to camel case
Detail
Digital root is the recursive sum of all the digits in a number.
Digital root - Wikipedia
The digital root (also repeated digital sum) of a natural number in a given radix is the (single digit) value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The pro
en.wikipedia.org
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
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.
<code>
function digital_root(n) {
let result = 0;
let splitNum = n.toString().split("").map(Number);
//숫자를 string으로 바꾸고, 배열에 하나씩 넣기
//map(Number)로 배열 안에 있는 값을 숫자로 변경! ★ (맨날 까먹으니까 꼭 기억하기)
while (splitNum.length > 1) {
splitNum.map((a, i) => {
result += a;
});
splitNum = result.toString().split("").map(Number);
result = 0;
if (splitNum.length === 1) {
//console.log("답:", Number(splitNum.join("")));
return Number(splitNum.join(""));
}
}
return result
}
<other>
function digital_root(n) {
return (n - 1) % 9 + 1;
}
function digital_root(n) {
if (n < 10) return n;
return digital_root(
n.toString().split('').reduce(function(acc, d) { return acc + +d; }, 0));
}
function digital_root(n) {
if (n < 10)
return n;
for (var sum = 0, i = 0, n = String(n); i < n.length; i++)
sum += Number(n[i]);
return digital_root(sum);
}
1을 빼고 9로 나눈 나머지에 1을 더하면 되는 간단한 공식이 있다는 것을 알게 되었다..!
답 보자마자 놀라서 바로 좋아요 눌러버린.. 세상에 똑똑한 사람들이 정말 많다.