js杨辉三角

/*可以直接复制,F12粘贴运行*/

var n = prompt("请输入阶数:", 9); n = n - 0;
var t1 = new Date();
var data = new Array();

function print(str) {
  if (typeof str == "number") {
    var width = n%10 + 60; //等边三角
    /* var width = str.toString().length * 10; //金字塔 */
    var sp = '<span style="padding:5px;display:inline-block;text-align:center;width:' + width + 'px;">' + str + '</span>';
    document.write(sp);
  } 
  else {
    document.write(str);
  }
}    
print('<div style=text-align:center;">');
  for (var i = 0; i < n; i++) {
    data[i] = new Array();
    for (var j = 1; j < i + 2; j++) {
      print(getNum(i, j));
    }
    print("<br/>");
  }
print("</div>");

var t2 = new Date();
print("<p style='text-align:center;'>耗时为(毫秒):" + (t2 - t1) + "</p>");

function getNum(x, y) {
  if ((y == 1) || (y == x + 1)) {
    data[x][y] = 1;
    return 1;
  }
  data[x][y] = data[x - 1][y - 1] + data[x - 1][y];
  return data[x - 1][y - 1] + data[x - 1][y];
}

 

posted @ 2019-09-30 16:50  TenFly  阅读(501)  评论(0编辑  收藏  举报