Java - 数字的递归总和及其工作原理
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37628457/
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
Java - Recursion sum of number and how it work
提问by scndjs
I am trying to write a recursive function that when I call with number 5 for example then the function will calculate the sum of all digits of five. 1 + 2 + 3 + 4 + 5 = 15
我正在尝试编写一个递归函数,例如,当我使用数字 5 调用该函数时,该函数将计算所有 5 位数字的总和。1 + 2 + 3 + 4 + 5 = 15
The current code always returns 0, how can the amount each time the n?
当前代码总是返回0,怎么每次n的量?
public class t {
public static void main(String[] args) {
System.out.println(num(5));
}
public static int num(int n) {
int sum = 0;
sum += n;
if (n == 0)
return sum;
return num(n - 1);
}
}
thank you.
谢谢。
回答by Tilak Maddy
Instead of setting the sum to 0
you can -
Do this:
而不是设置总和,0
你可以 - 这样
做:
public int sumUp(int n){
if (n==1)
return 1;
else
return sumUp(n-1)+n;
}
回答by Kevin Wallis
The problem is you set the sum always 0.
问题是您将总和设置为始终为 0。
public static void main(String[] args) {
System.out.println(num(5, 0));
}
public static int num(int n, int sum) {
if (n == 0) {
return sum;
}
sum += n;
return num(n - 1, sum);
}
回答by Mutlu
public static int withRecursion(List<Integer> list) {
int size = list.size();
int a=0;
if(list.isEmpty() == true) {
return 0;
}else {
a = a + list.get(0) + withRecursion(list.subList(1, size));
return a;
}
}