我在JS中遇到经典的Sum of Digits问题,并通过递归解决了它。该算法应该求和给定数字的位数,直到达到1位数的结果。
我想知道用模运算是否可能有一个更简单,更优雅的解决方案?
我只能想到这个:
// initialize var to accept input
/* possible inputs to test with:
3, -7231, 1020340567.89 */
let digits = 1020340567.89;
// create a function to filter input for minuses and floating points
function isPositiveInteger(value) {
return value !== '-' && value !== '.';
}
/* create a function to turn number input into string array,
split the string,
apply filter to remove '-' and '.'
and create a new array with the numbers */
function reduceToOneInt(digits) {
digits = digits.toString().split('').filter(isPositiveInteger).map(Number);
// apply reduce to the array of numbers
let sum = digits.reduce((accumulator, currentValue) => accumulator + currentValue);
// use ternary operator to check if result is one-digit num
// re-apply function if necessary
return sum < 10 ? sum : reduceToOneInt(sum);
}
// print output to console
console.log(reduceToOneInt(digits));