DEV Community

Pratik sharma
Pratik sharma Subscriber

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 (5)

Collapse
 
amer2023 profile image
Amer

this for java
for(int i = 1; i <= n ; i++){
int freesSpace = n - i ;
for(int a = 1; a<=freesSpace;a++){
System.out.print(" ");
} for(int b = 1; b<=i;b++){
System.out.print("#");
}
System.out.print("\n");
}
}

and all the HackerRan Solution it is in my GitHub
github.com/Al-Amer/HackerrankJava

Collapse
 
devsmitra profile image
Rahul Sharma • Edited

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

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);

}

Collapse
 
abdellahouffa profile image
Abdellah OUFFA

what's the issue with this one!! However, as soon as I run the code on the console it's given me the same output as the one on HackerRank but whenever I sumbit the code through hackerRnak' website ,the compiler message is telling me back the code I wrore was wrong!!
function drawTriangle(n) {
let j = "#";
let i = 1;
let myTriangle = "";
while (i <= n) {
myTriangle += "\n" + j;
j += "#";
i++;
}
console.log(myTriangle);
}