megazoid
megazoid

Reputation: 1145

breaking an integer into parts

I'm trying to add all the digits in an integer value until i get a value below 9 using Javascript.

for an example, if i have 198, I want to add these together like 1 + 9 + 8 = 18, and since 18 is higher than 9 add 1 +8 again = 9.

Upvotes: 1

Views: 796

Answers (3)

Mihran Hovsepyan
Mihran Hovsepyan

Reputation: 11088

function foo(var x)
{
    while(x > 9)
    {
        var y = 0;
        while(x!=0)
        {
            y += x%10;
            x = Math.floor(x/10);
        }
        x = y;
    }
    return x;
}

Upvotes: 1

anubhava
anubhava

Reputation: 785068

Rather than giving you full code I would just explain how to do it.

You can do modulo math by number%10 and subsequent int divide by 10 (number/10) until you get 0 to get all the digits of a number. Sum the individual digits and until sum > 9 repeat the above process in a loop.

Edit: okay here is the code for you:

<script>
var num=198;
n = num;
var sum;
do {
   sum = 0;
   while (n>0) {
      rem = (n % 10);
      sum += rem;
      n = (n - rem)/10;    
   }
   n = sum;
} while(sum>9);

alert("sum is: " + sum);

</script>

Upvotes: 3

NPE
NPE

Reputation: 500307

Here are two hints: (i % 10) gives the least significant decimal digit of i, while i /= 10 removes the least significant digit from i. The rest is left as an exercise for the reader.

Upvotes: 0

Related Questions