cocos creator基础-(三十一)超大数值计算

处理超出正常范围的整数,使用数组分段保存数据,逐项相加,满足条件就进位,需要注意数组下标越界
// large_number.js
// new  构造函数来模拟一个类

// 初始化的[0, 0, 0, 0, 0, 0, 9] --> 9 000 000 000 000 000 000 // [0, 999]
function _ajust_bit_value(bit_array) {
    // 处理进位,注意越界
    for (var i = 0; i < bit_array.length; i++) {
        while (bit_array[i] >= 1000) {
            bit_array[i] -= 1000;
            if (i + 1 >= bit_array.length) {
                this.value_set.push(0);
            }
            bit_array[i + 1] = bit_array[i + 1] + 1;
        }
    }
}

function large_number(value_array) {
    this.value_set = value_array;
    _ajust_bit_value(this.value_set);
}



// 当前的对对象 + rhs 赋值给当前这个对下岗
large_number.prototype.large_add = function(rhs) {
    // 补齐位数
    while (this.value_set.length < rhs.value_set.length) {
        this.value_set.push(0);
    }

    for (var i = 0; i < rhs.value_set.length; i++) {
        this.value_set[i] = this.value_set[i] + rhs.value_set[i];
    }

    _ajust_bit_value(this.value_set);
}

function _format_num(num) {
    if (num < 10) {
        return "00" + num;
    } else if (num < 100) {
        return "0" + num;
    } else {
        return "" + num;
    }
}

large_number.prototype.format_string = function() {
    var str_num = "" + this.value_set[this.value_set.length - 1];
    for (var i = this.value_set.length - 2; i >= 0; i--) {
        str_num = str_num + " " + _format_num(this.value_set[i])
    }

    return str_num
}

// test
/*var num1 = new large_number([0, 0, 0, 0, 0, 0, 9]);
var num2 = new large_number([0, 0, 0, 0, 0, 0, 8]);
num1.large_add(num2);
var num_str = num1.format_string();
console.log(num_str);*/
// end

module.exports = large_number;

 

posted @ 2019-04-04 15:17  orxx  阅读(1258)  评论(0编辑  收藏  举报