Sum of digits in C#

Viewed 105284

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 Answers

You could do it arithmetically, without using a string:

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

I use

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

It uses only 1 line of code.

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.

int num = 12346;
int sum = 0;
for (int n = num; n > 0; sum += n % 10, n /= 10) ;
 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;
 }

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.

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.

public static int SumDigits1(int n)
{
    int sum = 0;
    int rem;
    while (n != 0)
    {           
        n = Math.DivRem(n, 10, out rem);
        sum += rem;
    }
    return sum;
}

public static int SumDigits2(int n)
{
    int sum = 0;
    int rem;
    for (sum = 0; n != 0; sum += rem)   
        n = Math.DivRem(n, 10, out rem);        
    return sum;
}   

public static int SumDigits3(int n)
{
    int sum = 0;    
    while (n != 0)
    {
        sum += n % 10;
        n /= 10;
    }   
    return sum;
}   

Complete code in: https://dotnetfiddle.net/lwKHyA

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

If one wants to perform specific operations like add odd numbers/even numbers only, add numbers with odd index/even index only, then following code suits best. In this example, I have added odd numbers from the input number.

using System;
                    
public class Program
{
    public static void Main()
    {
        Console.WriteLine("Please Input number");
        Console.WriteLine(GetSum(Console.ReadLine()));
    }
    
    public static int GetSum(string num){
        int summ = 0;
        for(int i=0; i < num.Length; i++){
            int currentNum;
            if(int.TryParse(num[i].ToString(),out currentNum)){
                 if(currentNum % 2 == 1){
                    summ += currentNum;
                }
            }
       } 
       return summ;
    }
}

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