题目描述

给定一个字符串,将其打印成三角形:
image.png

题解

  1. function output(str) {
  2. const strLength = str.length;
  3. let totalLine = 0;
  4. let containerSize = 0;
  5. while (containerSize < strLength) {
  6. containerSize += totalLine * 2 + 1;
  7. totalLine++;
  8. }
  9. let result = '';
  10. let startIndex = 0;
  11. for (let curLine = 1; curLine <= totalLine; curLine++) {
  12. const endIndex = startIndex + 2 * curLine - 1;
  13. output += ' '.repeat(totalLine - curLine) + str.slice(startIndex, endIndex) + '\n';
  14. startIndex = endIndex;
  15. }
  16. console.log(result);
  17. }