开发者

How to calculate the average of digits of a number recursively? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

Specifically with Java, tough the solution should开发者_高级运维 basically work with other languages.

For example, 12345 would return 3.

Thanks.


Recursive solution:

double averageDigits(int number, int sum, int count) {
    if(number==0) {
        if(count==0) {
            return 0;
        }
        return ((double) sum) / ((double) count);
    }
    else {
        return averageDigits(number/10, sum + number % 10, ++count);
    }
}


If you have only integer numbers you might want to check mod "%" and simple division "/" and combine it with a loop to count and sum the number parts.


in pseudo code:

split the number in a list of digeds and then calc the avg recursiv

double avg(List<Integer> list) {
  if(list.length==0) return 0;
    else return (list.get(0)+ (avg(list.sublist(1)*(lisr.length()-1)))
               /list.length();
}


Don't know about java, in javascript, this would work

function avrg(arr){
   avrg.arr = avrg.arr || arr.slice();
   avrg.l = avrg.l || 1/arr.length;
   return arr.length ? (avrg.l*avrg.arr.pop()+avrg(avrg.arr)) : 0;
}


public String getAverage(String num) {
    try {
        Integer.parseInt(num);
    } catch (NumberFormatException e) {
        return "Invalid number";
    }
    int length = num.length();
    int total;
    int i;
    String[] digits = num.split("");
    for (String s : digits) {
        i = Integer.parseInt(s);
        total += i;
    }
    return (total / length).toString();
}


This does the trick:

public class DigitAverage {

    public static void main(String[] args) {
        System.out.println(digitAverage(12345));
    }

    private static double digitAverage(int remainder, int... depth) {

        boolean first = false;
        if (depth.length == 0) {
            depth = new int[] { 1 };
            first = true;
        } else {
            depth[0] = depth[0] + 1;
        }
        if (remainder < 10) {
            return remainder;
        }
        double result = remainder % 10 + digitAverage(remainder / 10, depth);
        if (first) {
            result = result / depth[0];
        }
        return result;
    }
}

Notice this function only requires the number as input, no internal 'bookkeeping' parameters of the recursion have be initialized by the caller.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜