java - 如何对数组值求和
问题描述
数组求和和返回有问题。算法也存在单值数组的问题。想法是将数字相加并形成一个新数组,直到只剩下一个值。例如数组 [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
}}
解决方案
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
推荐阅读
- reactjs - 反应无阴影规则处理
- macos - 如何在 Maven 中查找/创建 settings-security.xml 文件
- sql - 具有多列的 Order by 子句的语法不正确
- wpf - WPF: How to override PART_CellBorder style of GridViewCell?
- leaflet - 显示的缩放级别与平铺缩放级别:像素密度?
- java - How to convert UTC DateTime to another Time Zone using Java 8 library?
- forth - 如何在 Forth 中创建数组?
- ios - How to resume the CAAnimation group after cell reuse?
- reactjs - Redux Form - how to disable sync/async validation with a flag
- debugging - 在 Intellij 调试器断点中使用多个条件