如何将长整数转换成链并进行运算? 解决这个问题的方法可能是使用bigint库:“ big-integer”。
加载库:
var bigInt = require("big-integer");
String.prototype.add = function(val){
var x = this;
var y = val;
var result = "";
var len;
var lenx = x.length;
var leny = y.length;
var x1,y1,rem,div=0;
if(lenx>leny) len = lenx; else len = leny;
for(var i=0;i<len;i++){
if(i>=lenx) x1 = 0;
else x1 = parseInt(x[lenx-i-1]);
if(i>=leny) y1 = 0;
else y1 = parseInt(y[leny-i-1]);
rem = (x1+y1+div)%10;
div = Math.floor((x1 + y1+div)/10);
result = rem + result;
}
if(div>0){
result = div + result;
}
return result;
}
String.prototype.minus = function(val){
var vf = this.toString();
var val_ini =bigInt(val);
var val_fin =bigInt(vf);
var result = val_fin.minus(val_ini);
return result.toJSNumber();
}
示例:
var binary = '101111010110011011100100';
var binaryText = bigInt(binary);//Data converted to String
//Make addition
binaryText.add("1");
//Make substract
binaryText.min("1");