打印正三角形

1127次阅读  |  发布于5年以前

在屏幕上打印正三角形----O(N)复杂度

function tang(lv){
        function _t(lv){
            return (1 << 2*lv + 1) - 1;
        }

        var ret = [],t = 0, s = new Array(lv).join("0");
        for(var i = 0; i < lv - 1; i++){
            var x = _t(i);
            ret.push(s + (x ^ t).toString(2) + s);
            s = s.slice(1);
            t = x << 1;
        }
        ret.push(new Array(lv+1).join("* "));
        return ret;
    }

    document.write(tang(13).join().replace(/,/g,"<br/>").replace(/0/g,"&nbsp;").replace(/1/g,"*"));

上面的可能还只能输出有限的阶数(整数限制),下面的算法直接用字符串:

function tang(lv){

        var ret = [],c = "*", s = new Array(lv).join(" "), t = k = "";
        for(var i = 0; i < lv-1; i++){
            ret.push(s + c + t + s);
            s = s.slice(1);
            k = k ? k+"  " : " ";
            t = k + c;
        }
        ret.push(new Array(lv+1).join("* "));
        return ret;
    }

    document.write(tang(6).join("<br/>").replace(/ /g,"&nbsp"));

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8