Sum of digits in C#

前端 未结 18 2039
耶瑟儿~
耶瑟儿~ 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: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;
     }
    

提交回复
热议问题