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 39 40 41 42
| function solution(list) { if (list.length === 0) { return ""; } let result = []; let start = list[0]; let end = list[0]; for (let num of list.slice(1)) { if (num === end + 1) { end = num; } else { if (end - start >= 2) { result.push(`${start}-${end}`); } else { for (let j = start; j <= end; j++) { result.push(j.toString()); } } start = end = num; } }
if (end - start >= 2) { result.push(`${start}-${end}`); } else { for (let j = start; j <= end; j++) { result.push(j.toString()); } }
return result.join(","); }
|