joy_n
joy_n

Reputation: 1

How do I add the all digit of an integer until its a single digit number?

If my question was not clear. Here's the whole description:

Consider, n = 653; so I would like to add all the three digit like 6+5+3 = 14. But it still not an one digit number so I'll again do 1+4 = 5. Now it is as expected how can I do it? The 'n' can hold any integer. I've searched and found how to separate the digits. Than I started to write the code. But I got stuck. I also found something similar to my question but that wasn't clear to me. I'm not sharing my unsolved code because I want to complete it by myself. But also I am helpless. So It'll will be very helpful if you tell me how can I do that. Sorry, if the question doesn't comfort you.

Upvotes: 0

Views: 118

Answers (2)

Gerhard Stein
Gerhard Stein

Reputation: 1563

Okay, strategy is to apply here. How many numbers you need to sum up? In your case 3. Let's see for any number:

int sum = 0;
while( (n / 10) != 0 ) // break if the divsion is zero, meaning number go too small
{
  sum += (n%10); // tell me about the rest and sum it
  n = n / 10; // reduce n by dividing by ten
}

Now set n = sum and repeat. Yes, with a recursion it would be possible or just add another while loop outside.

If the number is smaller than the divisor itself, in case of integers, you obtain 0. With the modulo operation you get the rest of the division.

Using

sum = num % 9;

Seems to be a faster way to do so.

Upvotes: 0

Revolver_Ocelot
Revolver_Ocelot

Reputation: 8785

Do you need the result or the process. If all you care is result, then sum of sum of sum ... of digits can be found as:

int num = 653
int sum = num % 9;
if (sum == 0)
    sum = 9; 

Upvotes: 5

Related Questions