Sum of digits in C#

前端 未结 18 1968
耶瑟儿~
耶瑟儿~ 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:31
    int num = 12346;
    int sum = 0;
    for (int n = num; n > 0; sum += n % 10, n /= 10) ;
    
    0 讨论(0)
  • 2020-11-28 07:31

    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();
    
    0 讨论(0)
  • 2020-11-28 07:33
     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;
     }
    
    0 讨论(0)
  • 2020-11-28 07:34
    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;
    }
    
    0 讨论(0)
  • 2020-11-28 07:35
    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

    0 讨论(0)
  • 2020-11-28 07:37

    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.

    0 讨论(0)
提交回复
热议问题