Skip to content
Advertisement

Sum the digits of a number

If I want to find the sum of the digits of a number, i.e.:

  • Input: 932
  • Output: 14, which is (9 + 3 + 2)

What is the fastest way of doing this?

I instinctively did:

JavaScript

and I found this online:

JavaScript

Which is best to use for speed, and are there any other methods which are even faster?

Advertisement

Answer

Both lines you posted are fine, but you can do it purely in integers, and it will be the most efficient:

JavaScript

or with divmod:

JavaScript

Slightly faster is using a single assignment statement:

JavaScript

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement