Sum of digits in C#

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

    I would suggest that the easiest to read implementation would be something like:

    public int sum(int number)
    {
        int ret = 0;
        foreach (char c in Math.Abs(number).ToString())
            ret += c - '0';
        return ret;
    }
    

    This works, and is quite easy to read. BTW: Convert.ToInt32('3') gives 51, not 3. Convert.ToInt32('3' - '0') gives 3.

    I would assume that the fastest implementation is Greg Hewgill's arithmetric solution.

提交回复
热议问题