【问题标题】:How to sum up Array values如何对数组值求和
【发布时间】:2020-01-16 13:53:01
【问题描述】:

数组求和和返回有问题。算法也存在单值数组的问题。想法是将数字相加并形成一个新数组,直到只剩下一个值。例如数组 [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
}}

【问题讨论】:

  • 您遇到了单值数组的问题,因为如果它是单元素数组,您会跳过所有代码。似乎这最终也会引起问题;你应该返回那个单一的元素,因为它是答案。
  • 这就是我的JS版本得到的;似乎更正确。无论如何,你永远不会返回零以外的任何东西。这似乎是错误的。

标签: java arrays recursion


【解决方案1】:
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

【讨论】:

  • 与其为他们做功课,不如帮助他们而不是仅仅把答案交给他们,这样更有教育意义。
  • 我也要去,给我一些时间,而不是在我发布这篇文章的第二秒写评论^^
  • 另一种方法是只发布完整的答案。
【解决方案2】:

工作代码:

public class Main {
public static void main(String[] args) {
Main t = new Main();
System.out.println(t.count(new int[] {1,2,3,4,5})[0]); // 48
System.out.println(t.count(new int[] {2})[0]); // 2
System.out.println(t.count(new int[] {7,1,1,3,8,2,9,5,4,2})[0]); // 323
}
static int[] count(int[] t) {
if(t.length == 1)
    return t;
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 null;
    }
}

【讨论】:

  • IMO 这比已经接受的答案更糟糕(并且格式也更糟糕)。它也不遵循原始代码的约定。
猜你喜欢
  • 1970-01-01
  • 2014-07-28
  • 2017-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多