[英]Java - Recursion sum of number and how it work
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. 我试图写一个递归函数,当我用数字5调用时,函数将计算所有数字的总和为5。 1 + 2 + 3 + 4 + 5 = 15 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. 谢谢。
Instead of setting the sum to 0
you can - 您可以 - 而不是将总和设置为0
-
Do this: 做这个:
public int sumUp(int n){
if (n==1)
return 1;
else
return sumUp(n-1)+n;
}
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);
}
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.