Java 递归求和数组中的整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20253651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
recursively sum the integers in an array
提问by Maggie S.
I have a program that I'm trying to make for class that returns the sum of all the integers in an array using recursion. Here is my program thus far:
我有一个程序,我正在尝试为类编写一个程序,该程序使用递归返回数组中所有整数的总和。到目前为止,这是我的程序:
public class SumOfArray {
private int[] a;
private int n;
private int result;
public int sumOfArray(int[] a) {
this.a = a;
n = a.length;
if (n == 0) // base case
result = 0;
else
result = a[n] + sumOfArray(a[n-1]);
return result;
} // End SumOfArray method
} // End SumOfArray Class
But I'm getting three error which are all related, I believe, but I can't figure out why it is finding a type of null:
但是我得到了三个相关的错误,我相信,但我不明白为什么它会找到一种类型的空值:
SumOfArray.java:25: sumOfArray(int[]) in SumOfArray cannot be applied to (int)
result = a[n] + sumOfArray(a[n-1]);
^
SumOfArray.java:25: operator + cannot be applied to int,sumOfArray
result = a[n] + sumOfArray(a[n-1]);
^
SumOfArray.java:25: incompatible types
found : <nulltype>
required: int
result = a[n] + sumOfArray(a[n-1]);
^
3 errors
采纳答案by óscar López
The solution is simpler than it looks, try this (assuming an array with non-zero length):
解决方案比看起来更简单,试试这个(假设一个非零长度的数组):
public int sumOfArray(int[] a, int n) {
if (n == 0)
return a[n];
else
return a[n] + sumOfArray(a, n-1);
}
Call it like this:
像这样调用它:
int[] a = { 1, 2, 3, 4, 5 };
int sum = sumOfArray(a, a.length-1);
回答by NPE
The issue is that a[n-1]
is an int
, whereas sumOfArray
expects an arrayof int
.
问题是,a[n-1]
是int
,而sumOfArray
预计数组的int
。
Hint: you can simplify things by making sumOfArray
take the array and the starting (or ending) index.
提示:您可以通过sumOfArray
获取数组和开始(或结束)索引来简化事情。
回答by Steve Kuo
a
is an int
array. Thus a[n-1]
is an int
. You are passing an int
to sumOfArray
which expects an array and not an int
.
a
是一个int
数组。因此a[n-1]
是一个int
。您传递一个int
到sumOfArray
它期望的数组,而不是一个int
。
回答by Cruncher
a[n-1]
is getting the int at n-1, not the array from 0 to n-1.
在 n-1 处获取 int,而不是从 0 到 n-1 的数组。
try using
尝试使用
Arrays.copyOf(a, a.length-1);
instead
反而
回答by samach
Try this if you don't want to pass the length of the array :
如果你不想传递数组的长度,试试这个:
private static int sumOfArray(int[] array) {
if (1 == array.length) {
return array[array.length - 1];
}
return array[0] + sumOfArray(Arrays.copyOfRange(array, 1, array.length));
}
Offcourse you need to check if the array is empty or not.
当然,您需要检查数组是否为空。
回答by Nick13
This is the one recursive solution with complexity O(N).and with input parameter A[] only.
You can handle null and empty(0 length) case specifically as Its returning 0 in this solution. You throw Exception as well in this case.
这是一种复杂度为 O(N). 并且只有输入参数 A[] 的递归解决方案。
您可以特别处理 null 和 empty(0 length) 情况,因为它在此解决方案中返回 0。在这种情况下,您也会抛出异常。
/*
* Complexity is O(N)
*/
public int recursiveSum2(int A[])
{
if(A == null || A.length==0)
{
return 0;
}
else
{
return recursiveSum2Internal(A,A.length-1);
}
}
private int recursiveSum2Internal(int A[],int length)
{
if(length ==0 )
{
return A[length];
}
else
{
return A[length]+recursiveSum2Internal(A, length-1);
}
}
回答by Takao Shibamoto
How about this recursive solution? You make a smaller sub-array which contains elements from the second to the end. This recursion continues until the array size becomes 1.
这个递归解决方案怎么样?您制作了一个较小的子数组,其中包含从第二个到最后的元素。这种递归一直持续到数组大小变为 1。
import java.util.Arrays;
public class Sum {
public static void main(String[] args){
int[] arr = {1,2,3,4,5};
System.out.println(sum(arr)); // 15
}
public static int sum(int[] array){
if(array.length == 1){
return array[0];
}
int[] subArr = Arrays.copyOfRange(array, 1, array.length);
return array[0] + sum(subArr);
}
}
回答by Amandeep Singh
private static int sum(int[] arr) {
// TODO Auto-generated method stub
int n = arr.length;
if(n==1)
{
return arr[n-1];
}
int ans = arr[0]+sum(Arrays.copyOf(arr, n-1));
return ans;
}
回答by Naresh Krishnamoorthy
Simplified version:
简化版:
//acc -> result accumlator, len - current length of array
public static int sum(int[] arr, int len, int acc) {
return len == 0 ? acc : sum(arr, len-1, arr[len-1]+ acc);
}
public static void main(String[] args) {
int[] arr= { 5, 1, 6, 2};
System.out.println(sum(arr, arr.length, 0));
}