Don't say so much, just coding...
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. This is only applicable to the natural numbers.
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
def digital_root(n)
# ...
end
Test.assert_equals(digital_root(16), 7)
Test.assert_equals(digital_root(942), 6)
Test.assert_equals(digital_root(132189), 6)
Test.assert_equals(digital_root(493193), 2)
function digital_root(n) {
// ...
}
Test.assertEquals( digital_root(16), 7 )
Test.assertEquals( digital_root(456), 6 )
想法(1): 將傳進來的值,先切開之後進行相加
想法(2): 需要判斷如果是兩位數以上的話,還需要在進行上述的動作,可以聯想到遞迴
# Solution 1
def digital_root(n)
recursive = n.to_s.split('').map(&:to_i).sum
recursive >= 10 ? digital_root(recursive) : recursive
end
# Solution 2
def digital_root(n)
return n if n < 10
digital_root(n.to_s.chars.map(&:to_i).reduce(&:+))
end
# Solution 3
def digital_root(n)
n < 10 ? n : digital_root(n.to_s.chars.map(&:to_i).reduce(:+))
end
// Solution 1
function digital_root(n) {
recursive = n.toString().split('').reduce((sum, s) => {
return sum += Number(s);
}, 0);
return recursive < 10 ? recursive : digital_root(recursive);
}
// wait, what?
function digital_root(n) {
return (n - 1) % 9 + 1;
}