Sum of digits in C#

前端 未结 18 2083
耶瑟儿~
耶瑟儿~ 2020-11-28 07:21

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

18条回答
  •  感动是毒
    2020-11-28 07:49

    A while back, I had to find the digit sum of something. I used Muhammad Hasan Khan's code, however it kept returning the right number as a recurring decimal, i.e. when the digit sum was 4, i'd get 4.44444444444444 etc. Hence I edited it, getting the digit sum correct each time with this code:

     double a, n, sumD;
     for (n = a; n > 0; sumD += n % 10, n /= 10);
     int sumI = (int)Math.Floor(sumD);
    

    where a is the number whose digit sum you want, n is a double used for this process, sumD is the digit sum in double and sumI is the digit sum in integer, so the correct digit sum.

提交回复
热议问题