Sum of digits in C#

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

    You could do it arithmetically, without using a string:

    sum = 0;
    while (n != 0) {
        sum += n % 10;
        n /= 10;
    }
    

提交回复
热议问题