繁体   English   中英

我想在 java 中使用递归打印一系列

[英]i want to print a series using recursion in java

您必须使用递归打印模式。 给定一个输入 N,模式看起来像这样 N, ai, ai + 1, ai + 2,....., N. 如果 ai > 0 那么 ai + 1 = ai - 5 否则 ai + 1 = ai + 5 . 这将是从 N 到 ai <= 0 的递减序列,然后是直到 N 的递增序列。(请参阅示例测试用例以获得更好的解释)

输入格式 第一行包含一个 integer T 表示测试用例的数量。 对于接下来的 T 行中的每一行,每行包含一个 integer N。

Output 格式 对于新行上的每个测试用例,打印所需的模式。

约束 1 <= T <= 6

0 <= N <= 2000

示例输入

2

16

10

Output

16 11 6 1 -4 1 6 11 16

10 5 0 5 10

示例测试用例说明 对于第一个测试用例 N=16,它将是一个递减的序列,直到打印数量变为 <=0。 16 11 6 1 -4 在这点之后它将是一个递增的序列,直到打印数量变为 N 1 6 11 16 所以图案是 16 11 6 1 -4 1 6 11 16。

我的代码在下面,但我得到的 output 仅为 16,11,6,1,-4。 帮助我更正此代码

import java.util.Scanner;
public class Day3
{  
public static void series(int n,boolean b)
{
    int temp = n;
    boolean flag=b;
    System.out.println(temp+" ");
    if(flag==true)
        temp-=5;
    else if(flag==false)
        temp+=5;
    if(temp<=0)
        flag=false;
    if(temp<=n)
        series(temp,flag);
}
public static void main(String args[])
{
    Scanner sc = new Scanner(System.in);
    int t = sc.nextInt();
    while(t>0)
    {
        int n = sc.nextInt();
        series(n,true);
        t-=1;
    }
}
}

因为'n'在每种情况下都会发生变化。 您必须创建另一个变量并在其中保留第一个“n”,以控制温度是否小于“n”。

例如

import java.util.Scanner;
public class Day3
{  

int firstN = 0; //added that line

public static void series(int n,boolean b)
{
    int temp = n;
    boolean flag=b;
    System.out.println(temp+" ");
    if(flag==true)
        temp-=5;
    else if(flag==false)
        temp+=5;
    if(temp<=0)
        flag=false;
    if(temp<=firstN) //changed that line
        series(temp,flag);
}
public static void main(String args[])
{
    Scanner sc = new Scanner(System.in);
    int t = sc.nextInt();
    while(t>0)
    {
        int n = sc.nextInt();
        firstN = n; //added that line
        series(n,true);
        t-=1;
    }
}
}

还有一点小费;

您可以将(flag)用于(flag==true)

(!flag)表示(flag==false)

仅供参考:虽然这可以使用递归解决,但不使用递归可以更有效地解决。 就这么简单:

private static void printSeries(int N) {
      int T = N;
      while ( T >= 0 ) {
        System.out.print(T +  " ");
        T = T - 5;
      }
      while ( T <= N ) {
         System.out.print(T +  " ");
        T = T + 5;
      }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM