Sum of digits in C#

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

提交回复
热议问题