DEV Community šŸ‘©ā€šŸ’»šŸ‘Øā€šŸ’»

Pratik sharma
Pratik sharma

Posted on

StairCase | HackerRank solution in javascript

Problem Statement :

Input Format
A single integer ,n, denoting the size of the staircase.

Constraints: 0 < n <= 100

Output Format :

Print a staircase of size using # symbols and spaces.

Note: The last line must have spaces in it.

Example:
Sample Input : 6

Sample output

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

Enter fullscreen mode Exit fullscreen mode

Solution in javascript.

function staircase(n) {
    // Write your code here
    var line = '';
    for(let i = 1; i <n +1; i++) {
        line += Array(n-i).fill(' ').join('')
        line += Array(i).fill('#').join('')
        console.log(line)
        line = ''
    }

}
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
devsmitra profile image
Rahul Sharma • Edited on

padStart also can be used to solve this, for adding padding on string.

developer.mozilla.org/en-US/docs/W...

function staircase(n) {
  for (let i = 0; i < n; i++) {
    const line = Array(i + 1)
      .fill("#")
      .join("")
      .padStart(n);
    console.log(line);
  }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
biomathcode profile image
Pratik sharma Author

Ohh! okay thanks

Collapse
owaisniaz profile image
Muhammad Owais

function staircase(n) {
// Write your code here
let string = "";
for (let j = n; j > 0; j--) {
for (let i = 1; i <= n; i++) {
if (i < j) {
string += " ";
continue;
}
string += "#";
}
if (j === 1) {
continue;
}

string += "\n";
Enter fullscreen mode Exit fullscreen mode

}
console.log(string);

}

šŸŒš Life is too short to browse without dark mode