Sum of digits in C#

2019-01-06 13:12发布

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

17条回答
何必那么认真
2楼-- · 2019-01-06 13:43

Surprised nobody considered the Substring method. Don't know whether its more efficient or not. For anyone who knows how to use this method, its quite intuitive for cases like this.

string number = "17463";
int sum = 0;
String singleDigit = "";
for (int i = 0; i < number.Length; i++)
{
singleDigit = number.Substring(i, 1);
sum = sum + int.Parse(singleDigit);
}
Console.WriteLine(sum);
Console.ReadLine();
查看更多
放荡不羁爱自由
3楼-- · 2019-01-06 13:44
int num = 12346;
int sum = 0;
for (int n = num; n > 0; sum += n % 10, n /= 10) ;
查看更多
看我几分像从前
4楼-- · 2019-01-06 13:47

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.

查看更多
别忘想泡老子
5楼-- · 2019-01-06 13:52

The simplest and easiest way would be using loops to find sum of digits.

int sum = 0;
int n = 1234;

while(n > 0)
{
    sum += n%10;
    n /= 10;
}
查看更多
太酷不给撩
6楼-- · 2019-01-06 13:54

I would suggest that the easiest to read implementation would be something like:

public int sum(int number)
{
    int ret = 0;
    foreach (char c in Math.Abs(number).ToString())
        ret += c - '0';
    return ret;
}

This works, and is quite easy to read. BTW: Convert.ToInt32('3') gives 51, not 3. Convert.ToInt32('3' - '0') gives 3.

I would assume that the fastest implementation is Greg Hewgill's arithmetric solution.

查看更多
一纸荒年 Trace。
7楼-- · 2019-01-06 13:55
 public static int SumDigits(int value)
 {
     int sum = 0;
     while (value != 0)
     {
         int rem;
         value = Math.DivRem(value, 10, out rem);
         sum += rem;
     }
     return sum;
 }
查看更多
登录 后发表回答