Sum of digits in C#

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

    int n = 17463; int sum = 0;
    for (int i = n; i > 0; i = i / 10)
    {
    sum = sum + i % 10;
    }
    Console.WriteLine(sum);
    Console.ReadLine();
    

提交回复
热议问题