【问题标题】:Trying to understand how recursion works试图理解递归是如何工作的
【发布时间】:2017-10-02 21:44:08
【问题描述】:

下面的代码要求用户输入一个数字,然后将每个数字相加得到总和。例如,如果我输入 123,它将执行 (1+2+3),然后输出 6。我有递归方法: public static int sumDigits(long n) 但是我不确定它何时被调用或它是如何工作的,long n 声明是什么意思?

//this is my code
import java.util.Scanner;

 public class Practice {
    public static void main(String[] args) {

  Scanner input = new Scanner(System.in);

System.out.print("Enter a integer: ");

    long n = input.nextLong();
// Display the sum of all the digits in the integer
  System.out.println("The sum is: " + sumDigits(n));
}    

  //recrusve method that computes the sum of the digits in an integer
    public static int sumDigits(long n) {
       int sum = 0;

    while (n > 0)
      {
           sum += n % 10;
           n /= 10;
        }
     return sum;
   }
}

【问题讨论】:

  • 递归函数是调用自身的函数。 sumDigits 因此不是递归函数。
  • 您的代码中没有递归。如果您无法理解 long n 的含义,那么您将很难理解递归。
  • 显然你的问题与oracle无关。请查看 StackOverflow 网站添加到您的帖子中的标签,并根据需要进行编辑。这次为你做。
  • 你不应该问long n是什么意思。如果您可以访问 StackOverflow,我几乎可以肯定您也可以访问 Google。搜索一个有意义的短语,我尝试了“Java long data type”——它返回的第一个链接是这样的:docs.oracle.com/javase/tutorial/java/nutsandbolts/… 然后,习惯阅读文档——它会为你节省很多时间。
  • 这里没有明确的问题。也许您应该弄清楚如何将 sumdigits 函数重写为递归函数?听起来您需要更加熟悉基础知识才能解决这个问题。

标签: java recursion methods jgrasp


【解决方案1】:

你正在寻找这样的东西:

private long sumDigits(long n)
{
  if(n <= 0)
  {
    return 0;
  }
  return n + sumDigits(n - 1);
}

递归函数在操作中执行一个步骤,然后以某种结束条件调用自己以进行下一步。

在这种情况下,您希望将当前数字添加到它下面的所有数字的总和中,直到达到零。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-15
    • 2015-03-23
    • 1970-01-01
    • 2015-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-19
    相关资源
    最近更新 更多