首页 > 解决方案 > 如何对数组值求和

问题描述

数组求和和返回有问题。算法也存在单值数组的问题。想法是将数字相加并形成一个新数组,直到只剩下一个值。例如数组 [1,2,3,2] 变成 [3,5,5]、[8,10] 和最后 [18]。总结数组值并返回它的最佳方法是什么?

public class Arraytest {

int count(int[] t) {

    if (t.length > 1) {
        int[] tt = new int[t.length - 1];
        for (int i = 0; i < t.length - 1; i++) {
            tt[i] += t[i] + t[i + 1];
            System.out.println(tt[i]);
        }
        count(tt);
    }
    return 0;
}

}

public class Main {

public static void main(String[] args) {

Arraytest at = new Arraytest();
System.out.println(t.count(new int[] {1,2,3,4,5})); // 48
System.out.println(t.count(new int[] {2})); // 2
System.out.println(t.count(new int[] {7,1,1,3,8,2,9,5,4,2})); // 2538
}}

标签: javaarraysrecursion

解决方案


static int count(int[] t) {
    if(t.length == 1)
        return t[0];
    else if (t.length > 1) {
        int[] tt = new int[t.length - 1];
        for (int i = 0; i < t.length - 1; i++)
            tt[i] += t[i] + t[i + 1];
        return count(tt);
    }
    return 0;
}

最后你总是返回零而不是返回数组中的最后一个 int


推荐阅读