--> Staircase - Java HackerRank Solution

Staircase – Java HackerRank Solution

staircase image

Objective:

This problem focuses on constructing a visually formatted staircase by combining spaces and # symbols appropriately, Which is a practice problem for loops and string manipulation.

Problem Statement:

You need to write a function that takes an integer n and prints a staircase of height n. The stairs are right-aligned and consist of # symbols and spaces.

Input Format:

  • A single integer n representing the height of the staircase.

Output Format:

  • Print a staircase consisting of n lines, where each line i (1 ≤ i ≤ n) contains n-i spaces followed by i # symbols.
Example 1:

Input: n = 4
Output:

       #
      ##
     ###
    ####
   #####
  ######

Explanation: It has 4 levels, with each level right-aligned and progressively increasing in the number of # symbols.

Example 2:

Input: n = 3
Output:

       #
      ##
     ###

Explanation: It has 3 levels, with each level right-aligned and progressively increasing in the number of # symbols.

Example 3:

Input: n = 6
Output:

        #
       ##
      ###
     ####
    #####
   ######

Explanation: It has 6 levels, with each level right-aligned and progressively increasing in the number of # symbols.

Steps to Solve:

  1. Loop Through Levels: Use a loop to iterate through the levels of the staircase from 1 to n.
  2. Print Each Level: For each level i, print n-i spaces followed by i # symbols.
  3. Right-Align Each Level: Ensure that the # symbols are right-aligned by preceding them with the correct number of spaces.
staircase
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

    /*
     * Complete the 'staircase' function below.
     *
     * The function accepts INTEGER n as parameter.
     */

    public static void staircase(int n) {
    // Write your code here
        for(int i=0; i<n; i++){
            for(int j=n-1; j>=0; j--){
                if(j<=i) System.out.print("#");
                else System.out.print(" ");
            }
            System.out.println();
        }
    }

}

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

        int n = Integer.parseInt(bufferedReader.readLine().trim());

        Result.staircase(n);

        bufferedReader.close();
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *