Sum of digits in C#

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

    I thought I'd just post this for completion's sake:

    If you need a recursive sum of digits, e.g: 17463 -> 1 + 7 + 4 + 6 + 3 = 21 -> 2 + 1 = 3
    then the best solution would be

    int result = input % 9;
    return (result == 0 && input > 0) ? 9 : result;
    

提交回复
热议问题