【问题标题】:Use Recursion to Sum Digits until there is nothing left to sum使用递归对数字求和,直到没有什么可以求和
【发布时间】:2020-06-11 12:46:18
【问题描述】:

问题

数字根是一个数字中所有数字的递归和。

给定n,取n的数字之和。如果该值超过一位,则继续以这种方式减少,直到产生一位数。这仅适用于自然数。

我的代码

function digital_root(n) {
    
      let a = n.toString();
      let ai = a.split('');
      
      let bi = ai.map((item)=>{
        return parseInt(item);
      })

      let newArr = [];

      for(let i = 0; i < bi.length; i++){
        let c = bi[i];
        newArr.push(c);
      }
      
      let d = newArr.reduce((total, item)=>{
      return total + item;
      }, 0); 
   
  function recursive(d){
    if(d < 10){
      return d
  }

      a = d.toString();
      ai = a.split('');
      
      bi = ai.map((item)=>{
        return parseInt(item);
      });

      newArr = [];

      for(let i = 0; i < bi.length; i++){
        let c = bi[i];
        newArr.push(c);
      }
      
      d = newArr.reduce((total, item)=>{
      return total + item;
      }, 0); 

      return recursive(d);
      }
     
     
    return d;
}


console.log(digital_root(123));
console.log(digital_root(111));
console.log(digital_root(51024));

我的问题

由于某种原因,如果 d >= 9,代码似乎无法识别我需要再次运行该操作。

如何解决我已经完成的代码的问题?

也出于兴趣,你会怎么处理,我的回答似乎很复杂!

【问题讨论】:

    标签: javascript algorithm recursion


    【解决方案1】:

    让我们放入一些 cmets 看看发生了什么。

    function digital_root(n) {
        // convert multiple digit number to String
        let a = n.toString();
        // split the String into an array of single digit Strings
        let ai = a.split('');
        // convert String array into int array  
        let bi = ai.map((item)=>{
            return parseInt(item);
        })
        
        // it looks like you are just copying the array here, 
        //I don't think there is a need for that
        //  let newArr = [];
    
        //  for(let i = 0; i < bi.length; i++){
        //    let c = bi[i];
        //    newArr.push(c);
        //  }
          
        // reduce the int array to the sum of its digits
        let d = bi.reduce((total, item)=>{
            return total + item;
        }, 0); 
       
        // That should be it, now just print it or recurse it
        if (d < 10) {
            return d;
        }
        // here is how you recurse, call the method from within the method
        return digital_root(d);
    
        // I'm not sure what you are doing here, you are repeating code
        // this is not how recursion works
    //        function recursive(d){
    //            if(d < 10){
    //              return d
    //            }
    
    //            a = d.toString();
    //            ai = a.split('');
          
    //            bi = ai.map((item)=>{
    //                return parseInt(item);
    //            });
    
    //            newArr = [];
    
    //            for(let i = 0; i < bi.length; i++){
    //                let c = bi[i];
    //                newArr.push(c);
    //            }
          
    //            d = newArr.reduce((total, item)=>{
    //                return total + item;
    //            }, 0); 
    
    //            return recursive(d);
    //        }
    //        return d;
    }
    
    
    console.log(digital_root(123));
    console.log(digital_root(111));
    console.log(digital_root(51024));

    【讨论】:

    • 真的很有用,哈哈意识到我的代码是多么的垃圾:'D以一种很好的方式!
    【解决方案2】:

    你永远不会调用你创建的递归函数,将return d替换为return recursive(d);

    我会怎么做:

    function digital_root(n){
       return n < 10 ? n : digital_root(String(n).split('').reduce((acc,val) => acc+(val|0),0));
    }
    

    【讨论】:

    • 谢谢!我很惊讶它的工作(因为我理解递归函数在“digital_root”函数中。因此,当递归函数返回时,我没想到“digital_root”函数会返回内部递归函数的结果。为什么那行得通吗?:)
    • @AndrewNeedsHelp:这将返回 n(如果 n digital_root 的结果(如果 n >= 10)。它类似于return n % 2 == 0 ? 'even' : 'odd'。条件表达式cond ? res : alt 产生resalt。最后,return 语句仅返回该条件表达式的结果。
    【解决方案3】:

    除了Photon说的,这里还有一个更简单的解决方案

    function sum(n) {
        if (n <= 9) {
            return n;
        } else {
            return sum((n % 10) + sum(n / 10));
        }
    }
    
    >>> sum(156)
    ... 3
    >>> sum(9999)
    ... 9
    >>> sum(10)
    ... 1
    

    【讨论】:

    • Javascript 没有整数除法,所以你应该改用Math.floor(n / 10)。还有sum(x + sum(y)) === sum(x + y),所以最后一行应该是return sum(n % 10 + Math.floor(n / 10))
    猜你喜欢
    • 2011-02-14
    • 2016-09-22
    • 1970-01-01
    • 1970-01-01
    • 2023-01-23
    • 1970-01-01
    • 2021-02-25
    • 2016-02-25
    • 2017-10-24
    相关资源
    最近更新 更多