Sum of digits in C#

前端 未结 18 1966
耶瑟儿~
耶瑟儿~ 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:24
    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

    0 讨论(0)
  • 2020-11-28 07:28
    int j, k = 1234;
    for(j=0;j+=k%10,k/=10;);
    
    0 讨论(0)
  • 2020-11-28 07:28

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

    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.

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

    You could do it arithmetically, without using a string:

    sum = 0;
    while (n != 0) {
        sum += n % 10;
        n /= 10;
    }
    
    0 讨论(0)
  • 2020-11-28 07:31

    I use

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

    It uses only 1 line of code.

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