DeveloperJourney
DeveloperJourney

Reputation: 47

Counting the sum of digits in a loop

I have a problem making an algorithm count the sum of digits that were used in a loop.

Let me outline the basic principles :

1 2 3 4 5 6 7 8 9 = 9 Digits
1 2 3 4 5 6 7 8 9 10 = 11 Digits

I have try to search for a solution for a bit, but I could not find a solution that would be suitable.

The base idea is that I have a known number n that will represent the end of the digit count. Count begins from 1 so 1 <= n <= 10000.

The first thing that came to my mind was counting the digit amount:

while(numdig != 0) {
    numDig = n/10;
    digCount++;
}

and continue on with a loop in a loop but I found myself confused on the second loop . After that I thought of a cycle that would use a lot of if`s which would be a very incorrect way of solving the problem.

I hope the problem is understandable.
Thank you

Upvotes: 0

Views: 659

Answers (3)

Vimal
Vimal

Reputation: 456

This could be another approach

int getDigitCount ( int val )
{
   stringstream ss;
   ss << val;
   string valstr = ss.str ();
   return valstr.length();
}


int main ( int argc, char** argv )
{
   int n;
   cout << "Enter a number between 1 and 10000 " << endl;
   cin >> n;
   long digitcount = 0;
   for ( int i = 1; i <= n; i ++ )
   {
      digitcount += getDigitCount ( i );
   }

   cout << "Digit Count =" << digitcount << endl;
   return 0;
}

Upvotes: 1

braindf
braindf

Reputation: 764

You can try use snprintf( which returns the number of characters that were written). Would be something like:

//read numdig
char buff[6]; // max of 5 digits and the '\0'
digCount += snprintf(buff,6, "%d", numdig);

Upvotes: 3

John Hascall
John Hascall

Reputation: 9416

Perhaps this will prove useful (separating the digit counting into its own function) in helping you write your program.

/* return the number of digits in the number i */
int ndigits ( int i ) {
    int n = 1;

    if (i < 0) i = -i;
    while (i >= 10) { ++n; i /= 10; }
    return n;
}

Upvotes: 3

Related Questions