Sum of digits in C#

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

    I like the chaowman's response, but would do one change

    int result = 17463.ToString().Sum(c => Convert.ToInt32(c));
    

    I'm not even sure the c - '0', syntax would work? (substracting two characters should give a character as a result I think?)

    I think it's the most readable version (using of the word sum in combination with the lambda expression showing that you'll do it for every char). But indeed, I don't think it will be the fastest.

提交回复
热议问题