zoukankan      html  css  js  c++  java
  • 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;
  • 相关阅读:
    LinkedList源码浅析
    ArrayList/Vector/Stack底层分析
    遮罩层
    重写alert方法,去掉地址显示
    继承属性的函数
    为什么手机网页点击输入框的瞬间会出现灰色背景呢?怎么去掉灰色背景?
    伪类before和after
    五星好评
    String[]字符串数组,按字典顺序排列大小
    jquery ajax的load()方法和load()事件
  • 原文地址:https://www.cnblogs.com/orxx/p/10655020.html
Copyright © 2011-2022 走看看