Sum of digits in C#

Xn0vv3r picture Xn0vv3r · Jan 26, 2009 · Viewed 99.9k times · Source

What's the fastest and easiest to read implementation of calculating the sum of digits?

I.e. Given the number: 17463 = 1 + 7 + 4 + 6 + 3 = 21

Answer

Greg Hewgill picture Greg Hewgill · Jan 26, 2009

You could do it arithmetically, without using a string:

sum = 0;
while (n != 0) {
    sum += n % 10;
    n /= 10;
}