Sum of digits in C#

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

提交回复
热议问题