用 JavaScript 递归方式将数字之和减少为一位数

javascriptweb developmentobject oriented programming更新于 2025/10/2 22:36:17

我们必须编写一个函数,该函数接受一个数字并不断添加其数字,直到结果不是一位数,当我们得到一位数时,我们将返回它。

此代码非常简单,我们编写一个递归函数,不断添加数字,直到数字大于 9 或小于 -9(我们将单独处理符号,这样我们就不必编写两次逻辑)

示例

const sumRecursively = (n, isNegative = n < 0) => {
   n = Math.abs(n);
   if(n > 9){
      return sumRecursively(parseInt(String(n).split("").reduce((acc,val) => {
         return acc + +val;
      }, 0)), isNegative);
   }
   return !isNegative ? n : n*-1;
};
console.log(sumRecursively(88));
console.log(sumRecursively(18));
console.log(sumRecursively(-345));
console.log(sumRecursively(6565));

输出

控制台中的输出将是 −

7
9
-3
4

相关文章


有用资源