Sum of digits in C#


Question

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

1
36
1/26/2009 6:18:47 AM

Accepted Answer

You could do it arithmetically, without using a string:

sum = 0;
while (n != 0) {
    sum += n % 10;
    n /= 10;
}
95
1/26/2009 6:22:20 AM

I use

int result = 17463.ToString().Sum(c => c - '0');

It uses only 1 line of code.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon