Sum of digits in C#

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

    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();
    

提交回复
热议问题