Hav*_*ead 4 java methods recursion
如何使用递归使函数返回所有数字的总和,直到它变成 1 位数字?我能够创建一个函数来获取所有数字的总和,但似乎无法找到一种方法来递归地对总和本身的数字求和:
class sum_of_digits
{
static int sum_of_digit(int n)
{
if (n == 0)
return 0;
return (n % 10 + sum_of_digit(n / 10));
}
public static void main(String args[])
{
int num = 12345;
int result = sum_of_digit(num);
System.out.println("Sum of digits in " +
num + " is " + result);
}
}
Run Code Online (Sandbox Code Playgroud)
This code prints the sum of '12345', which is 15. But I need to change it so it prints the sum of 1 + 5, which is 6.
您认为无需其他方法就可以使其工作吗?
为什么我们不能让递归为我们完成工作并简单地说:
static int sum_of_digit(int n)
{
if (n < 10)
return n;
return sum_of_digit(n % 10 + sum_of_digit(n / 10));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2089 次 |
| 最近记录: |