-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathzigzag_conversion.js
More file actions
38 lines (35 loc) · 870 Bytes
/
zigzag_conversion.js
File metadata and controls
38 lines (35 loc) · 870 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* @author Anirudh Sharma
*/
var convert = function (s, numRows) {
// Base conditions
if (s === null || numRows <= 0) {
return "";
}
if (numRows === 1) {
return s;
}
// Resultant String
let result = ""
// Step size
const step = 2 * numRows - 2;
// Loop for each row
for (let i = 0; i < numRows; i++) {
// Loop for each character in the row
for (let j = i; j < s.length; j += step) {
result += s[j];
if (i != 0 && i != numRows - 1 && (j + step - 2 * i) < s.length) {
result += s[j + step - 2 * i];
}
}
}
return result;
};
let s = "PAYPALISHIRING"
let numRows = 3;
console.log(convert(s, numRows));
numRows = 4;
console.log(convert(s, numRows));
s = "ANIRUDHSHARMAISGREAT";
numRows = 5;
console.log(convert(s, numRows));