Algorithm for digit summing?

我是研究僧i 提交于 2019-12-02 22:16:29

Because 10-1=9, a little number theory will tell you that the final answer is just n mod 9. Here's code:

ans = n%9;
if(ans==0 && n>0) ans=9; 
return ans;

Example: 18268%9 is 7. (Also see: Casting out nines.)

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;
}

Doesn't work with negative numbers, but I don't know how you would handle it anyhow. You can also change f(x) to be iterative:

sum( x ) =
    while ( ( x = f( x ) ) >= 10 );
    return x;

f( x ) = 
    if ( x >= 10 ) return f( x / 10 ) + x % 10
    return x

You can also take advantage of number theory, giving you this f(x):

f( x ) =
    if ( x == 0 ) return 0
    return x % 9
  1. Mod the whole number by 10.
  2. Add the number to an array.
  3. Add the whole array.
int number = 18268;
int total = 0;

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

this is from a really long time ago, but the best solution i have for this is:

int digitSum(int num){
    if (num < 10) return num;
    else return (n-1)%9+1;
}

I don't know how much better this is,but it will account for the divisible by 9 numbers easily. Just a cool algorithm.

    private static int sum(long number) {
    int sum = 0;
    if (number == 0) {
        return 0;
    }
    do {
        int last = (int) (number % 10);
        sum = (sum + last) % 9;
    } while ((number /= 10) > 0);

    return sum == 0 ? 9 : sum;
}
public int DigitSum(long n)
  {
     return (int)(1 + (n - 1) % 9);
  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!