Sum all the digits of a number Javascript

后端 未结 4 2105
囚心锁ツ
囚心锁ツ 2020-11-27 06:21

I am newbie.

I want to make small app which will calculate the sum of all the digits of a number.

For example, if I have the number 2568, the app will calcul

4条回答
  •  广开言路
    2020-11-27 06:47

    let's try recursivity

    function sumDigits(n) {
      if (n < 10) return n
      return sumDigits(n % 10 + sumDigits(Math.floor(n / 10)))
    }
    
    sumDigits(2) // 2
    sumDigits(2568) // 3
    

提交回复
热议问题