Algorithm for digit summing?

2019-03-11 05:51发布

I'm searching for an algorithm for Digit summing. Let me outline the basic principle:

Say you have a number: 18268.

1 + 8 + 2 + 6 + 8 = 25

2 + 5 = 7

And 7 is our final number. It's basically adding each number of the whole number until we get down to a single (also known as a 'core') digit. It's often used by numerologists.

I'm searching for an algorithm (doesn't have to be language in-specific) for this. I have searched Google for the last hour with terms such as digit sum algorithm and whatnot but got no suitable results.

8条回答
Explosion°爆炸
2楼-- · 2019-03-11 06:26

I would try this:

int number = 18268;
int core = number;
int total = 0;

while(core > 10)
{
   total = 0;
   number = core;
   while(number > 0)
   {
      total += number % 10;
      number /= 10;
   }

   core = total;
}
查看更多
Melony?
3楼-- · 2019-03-11 06:35
int number = 18268;
int total = 0;

while(number > 0)
{
   total += number % 10;
   total = total%10;
   number /= 10;
}
查看更多
登录 后发表回答