-1

I have to use a static method TotalAverage(int n) that would calculate the average digit total of the numbers 0 + 1 + 2 + .... + n. So that totalAverage(19) would be calculated as (0 + 1 + ... + 9 + 1 + ... + 10) / 20.0. I managed to do it for the most part using the following code:

public static double TotalAverage(int n) {
    double total = 0;
    int count = 0;
    while (n >= 0) {
        total += n % 10;
        n = n - 1;
        count++;
    }
    return total / count;
}

It works for numbers up to 9, but I get incorrect results for larger numbers. I realise that once the while statements gets to 10 % 10 it adds 0 to the total and not a 10, but I can't figure out how to do it correctly.

Captain Man
  • 6,997
  • 6
  • 48
  • 74
jack
  • 45
  • 1
  • 6
  • 4
    Hint: the sum of values from 0 to n is equal to (n^2 + n)/2. That eliminates the need for a loop. – Makoto Oct 26 '15 at 20:52
  • The problem is that I don't need to calculate 19+18+17+16 + ... + 0, but in the way that is enclosed in the question. – jack Oct 26 '15 at 20:55
  • @jack From your description it is not clear what should happen, maybe you should add the details for a bigger number like: totalAverage(33) – dan Oct 26 '15 at 20:59
  • What is this supposed to do? Average digit total makes it sound like 19 would be average of 1 and 9 (137 would be 1, 3, and 7), but then you say it's 0 through the given, but when you explain 19 you say 0 through 9 then 1 through 10? Please clear this up. **All that aside,** what you really seem to want is [how to get the nth digit from an int](http://stackoverflow.com/questions/19194257/return-the-nth-digit-of-a-number) – Captain Man Oct 26 '15 at 20:59
  • totalAverage(19) should return (0+1+2+3+4+5+6+7+8+9+1+2+3+4+5+6+7+8+9+10) / 20 = 5.0 The way I've done it now sums all these numbers but not the 10 as 10%10 adds 0 to the total. – jack Oct 26 '15 at 21:03
  • @jack I get that, but can you explain it for another number like 25 and 4 so we can better understand what this does, or better phrase it? – Captain Man Oct 26 '15 at 21:05
  • It might help to phrase it as the average digit sum **up to** an integer. – Linus Oct 26 '15 at 21:09

2 Answers2

1

If you're looking to sum all digits of a number then the error in your code is

total += n % 10;

which only get the ones digit from n. Use some loop to get all digits from n without modifying it (because if you modify n your outer loop will break). Try:

int temp = n;
while(temp>0) {
   total += temp % 10; //add next digit
   temp /= 10;
}
Linus
  • 894
  • 7
  • 13
0

You could use a separate method for digit sum. Something like this would work.

private static int digitSum(int a) {
    return a < 10 ? a : a%10 + digitSum(a/10);
}

Then you can replace the line

total += n % 10

with

total += digitSum(n);
Paul Boddington
  • 37,127
  • 10
  • 65
  • 116