Is there possibility of sum of ArrayList without looping

后端 未结 13 1401
无人共我
无人共我 2020-11-27 04:24

Is there possibility of sum of ArrayList without looping?

PHP provides sum(array) which will give the sum of array.

The PHP code is

13条回答
  •  情深已故
    2020-11-27 04:58

    The only alternative to using a loop is to use recursion.

    You can define a method like

    public static int sum(List ints) {
       return ints.isEmpty() ? 0 : ints.get(0) + ints.subList(1, ints.length());
    }
    

    This is very inefficient compared to using a plain loop and can blow up if you have many elements in the list.

    An alternative which avoid a stack overflow is to use.

    public static int sum(List ints) {
        int len = ints.size();
        if (len == 0) return 0;
        if (len == 1) return ints.get(0);
        return sum(ints.subList(0, len/2)) + sum(ints.subList(len/2, len));
    }
    

    This is just as inefficient, but will avoid a stack overflow.


    The shortest way to write the same thing is

    int sum = 0, a[] = {2, 4, 6, 8};
    
    for(int i: a) {
        sum += i;
    }
    
    System.out.println("sum(a) = " + sum);
    

    prints

    sum(a) = 20
    

提交回复
热议问题