Alex Rivera | Logout

Sum of digits in C#

Asked 2009-01-26T06:18:47.923
48

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

Edit
Report

1 Answer

14
int num = 12346;
int sum = 0;
for (int n = num; n > 0; sum += n % 10, n /= 10) ;
answered 2009-01-26T07:51:57.953

Your Answer