Keep track of how many times a recursive function was called

后端 未结 9 1937
醉梦人生
醉梦人生 2021-02-02 05:03



        
9条回答
  •  情歌与酒
    2021-02-02 05:45

    Another approach, since you produce all the numbers, is to use a generator.

    The last element is your number n reduced to a single digit number and to count how many times you have iterated, just read the length of the array.

    const digits = [...to_single_digit(39)];
    console.log(digits);
    //=> [27, 14, 4]


    Final thoughts

    You may want to consider having a return-early condition in your function. Any numbers with a zero in it will return zero.

    singleDigit(1024);       //=> 0
    singleDigit(9876543210); //=> 0
    
    // possible solution: String(n).includes('0')
    

    The same can be said for any numbers made of 1 only.

    singleDigit(11);    //=> 1
    singleDigit(111);   //=> 1
    singleDigit(11111); //=> 1
    
    // possible solution: [...String(n)].every(n => n === '1')
    

    Finally, you didn't clarify whether you accept only positive integers. If you accept negative integers then casting them to strings can be risky:

    [...String(39)].reduce((x, y) => x * y)
    //=> 27
    
    [...String(-39)].reduce((x, y) => x * y)
    //=> NaN
    

    Possible solution:

    const mult = n =>
      [...String(Math.abs(n))].reduce((x, y) => x * y, n < 0 ? -1 : 1)
    
    mult(39)
    //=> 27
    
    mult(-39)
    //=> -27
    

提交回复
热议问题