Как напечатать следующий узор, используя число logi c? - PullRequest
0 голосов
/ 19 июня 2020

Я хочу напечатать следующий вывод, учитывая n как input = 4:

                        1
                1       2
        1       2       3
1       2       3       4

Количество строк должно совпадать с вводом Вот что у меня есть до сих пор, но я не могу поймите это правильно: (

for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n - i; j++)
                System.out.print("\t"+j);
        }

Ответы [ 2 ]

1 голос
/ 19 июня 2020

Попробуйте:

for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n - i; j++) // Print tab as many times as n-1
                System.out.print("\t");

            for (int j = 1; j <= i; j++)
                System.out.print(j + "\t"); // Print 1 to i

            System.out.println(); // Go to next line
        }
0 голосов
/ 19 июня 2020

Попробуйте это. Надеюсь, понятно.

    int n = 4;
    // Basically we need to create n different lines, we can use a StringBuilder for that purpose
    StringBuilder str = new StringBuilder();

    // each line contains up to n different digits (count " " as a digit)
    // so the for loop should cover from 0 to n - 1 (i < n achieves that, just the same as i <= n - 1)
    for (int i = 0; i < n; i++){

        /*
        how many " " spaces do we need? as we can observe given the desired output
        in each line (from top to bottom) the number of blanks decreases from n - 1 (in the firs row we have 3 blanks)
        to no blank spaces at all (second line we have 2 blanks)
        It's easy to see the pattern:
        Line 1: 3 blanks -> blanks = n - 1 - i = 4 - 1 - 0 = 3 GOOD
        Line 2: 2 blanks -> blanks = n - 1 - i = 4 - 1 - 1 = 2 GOOD
        Line 3: 1 blank -> blanks = n - 1 - i = 4 - 1 - 2 = 1 GOOD
        Line 4: 0 blank -> blanks = n - 1 - i = 0 GOOD
        */
        int blanks = n - 1 - i;

        // now that we know how many blanks each specific line has, let's build the string
        for(int j = 0; j < blanks; j++){
            str.append(" \t");
        }
        /*
        at this point we have finished setting the blanks
        now we need to fill the remainder space (n - blanks) with numbers
        in the first line we need only a 1
        in the second line we need a 1 and a 2
        in the third line we need a 1, a 2 and a 3
        in the fourth line we need a 1, a 2, a 3 and 4
        The pattern here is also clear now.
        Line 1: we had 3 blanks -> numbers = n - blanks = 1 GOOD
        Line 2: we had 2 blanks -> numbers = n - blanks = 2 GOOD
        ..and so on..
        All we need is a for loop to add those numbers to the string
        */
        for(int j = 1; j <= n - blanks; j++){
            str.append(j).append("\t");
        }
        // Here we reach the end of a line, so we add a "\n" to jump to the next line
        str.append("\n");
    }

    System.out.print(str);
...