Mark Spencer Mark Spencer - 3 months ago 9
C Question

How to implement this exercise (dynamic array)?

I'm having like an assesment exercise.

So given a Number, for example 12345, I must find out the sum sequence of the digits of the given number (1 + 2 +3 + 4 +5) and then add to it the result (15), and repeat this till the sum sequence of the last number is a digit (in this case is 6).

Example : 12345 + 15 + 6 = 12366;

666 + 24 + 6 = 696;

I've been thinkig to store the digits in an array, but then I realized the array's size is static. Now I'm thinking to make a linked list, but I'm not really sure. Does it involve linked lists?

Just guide me to the right path. What should I use?

Answer

There's no magic needed here. Just do the obvious computation on integers:

int reduce(int n)
{
    int result = 0;
    while (n != 0) { result += n % 10; n /= 10; }
    return result;
}

int your_problem(int n)
{
    int result = n;
    while (n >= 10) { n = reduce(n); result += n; }
    return result; 
}