大整数相加

function repeatStr(ch, n){
            var str = "";
            for(var i=0; i< n; i++){
                str += ch;
            }
            return str;
        }
        function bigSum(a,b){
            a = String(a);
            b = String(b);

            var distLen = Math.abs(a.length - b.length);
            if(a.length > b.length){
                b = repeatStr("0",distLen) + b;
            }else{
                a = repeatStr("0",distLen) + a;
            }
            //console.log(b)
            var result = "";
            var addPoint = 0;
            var j = 1;
            for(var i=0; i < a.length; i++){

                var tmp = parseInt(a.charAt(a.length - j),10)
                        + parseInt(b.charAt(b.length - j), 10)
                        + addPoint ;
                if(tmp >= 10){
                    addPoint = 1;
                    tmp -= 10;
                }else{
                    addPoint = 0
                }
                j++;
                result =  tmp + result;
            }
            if(addPoint == 1){
                return "1" + result;
            }
            return result;
        }

        console.log(bigSum("1","999"))

你可能感兴趣的:(JavaScript)