Sum of digits in C#

2019-01-06 13: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

回答1:

You could do it arithmetically, without using a string:

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


回答2:

I use

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

It uses only 1 line of code.



回答3:

For integer numbers, Greg Hewgill has most of the answer, but forgets to account for the n < 0. The sum of the digits of -1234 should still be 10, not -10.

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

It the number is a floating point number, a different approach should be taken, and chaowman's solution will completely fail when it hits the decimal point.



回答4:

int num = 12346;
int sum = 0;
for (int n = num; n > 0; sum += n % 10, n /= 10) ;


回答5:

 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;
 }


回答6:

I like the chaowman's response, but would do one change

int result = 17463.ToString().Sum(c => Convert.ToInt32(c));

I'm not even sure the c - '0', syntax would work? (substracting two characters should give a character as a result I think?)

I think it's the most readable version (using of the word sum in combination with the lambda expression showing that you'll do it for every char). But indeed, I don't think it will be the fastest.



回答7:

I thought I'd just post this for completion's sake:

If you need a recursive sum of digits, e.g: 17463 -> 1 + 7 + 4 + 6 + 3 = 21 -> 2 + 1 = 3
then the best solution would be

int result = input % 9;
return (result == 0 && input > 0) ? 9 : result;


回答8:

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.



回答9:

private static int getDigitSum(int ds)
{
    int dssum = 0;            
    while (ds > 0)
    {
        dssum += ds % 10;
        ds /= 10;
        if (dssum > 9)
        {                
            dssum -= 9;
        }
    }
    return dssum;
}

This is to provide the sum of digits between 0-9



回答10:

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;
}


回答11:

int j, k = 1234;
for(j=0;j+=k%10,k/=10;);


回答12:

while(ino!=0 )
{
  digit=(ino%10));
  printf("%d",digit);
  ino=ino/10;   
}           

for an array like this i/p:10 25 712 65

this wont work you have to try other logic if someone got one please post it for addition of array elements.



回答13:

#include <stdio.h>

int main (void) {

    int sum = 0;
    int n;
    printf("Enter ir num ");
    scanf("%i", &n);

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

    printf("Sum of digits is %i\n", sum);

    return 0;
}


回答14:

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.



回答15:

int n = 17463; int sum = 0;
for (int i = n; i > 0; i = i / 10)
{
sum = sum + i % 10;
}
Console.WriteLine(sum);
Console.ReadLine();


回答16:

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();


回答17:

static int SumOfDigits(int num)
{
    string stringNum = num.ToString();
    int sum = 0;
    for (int i = 0; i < stringNum.Length; i++)
    {
      sum+= int.Parse(Convert.ToString(stringNum[i]));

    }
    return sum;
}