Sum all the digits of a number Javascript

后端 未结 4 2090
囚心锁ツ
囚心锁ツ 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条回答
  •  -上瘾入骨i
    2020-11-27 06:33

    How about this simple approach using modulo 9 arithmetic?

    function sumDigits(n) {
      return (n - 1) % 9 + 1;
    }
    

提交回复
热议问题