add method
Return a new Big whose value is the value of this Big plus the value of Big y
.
Implementation
Big add(dynamic y) {
var yBig = Big(y);
int e, k;
List<int> t;
Big x = this;
// Signs differ?
if (x.s != yBig.s) {
yBig.s = -yBig.s;
return x.sub(yBig);
}
var xe = x.e, xc = x.c, ye = yBig.e, yc = yBig.c;
// Either zero?
if (!xc.isElementIsValid(0) || !yc.isElementIsValid(0)) {
if (!yc.isElementIsValid(0)) {
if (xc.isElementIsValid(0)) {
yBig = Big(x);
} else {
yBig.s = x.s;
}
}
return yBig;
}
xc = [...xc];
// Prepend zeros to equalise exponents.
e = xe - ye;
if (e != 0) {
if (e > 0) {
ye = xe;
t = yc;
} else {
e = -e;
t = xc;
}
t.reverse();
for (; e-- > 0;) {
t.add(0);
}
t.reverse();
}
// Point xc to the longer array.
if (xc.length - yc.length < 0) {
t = yc;
yc = xc;
xc = t;
}
e = yc.length;
// Only start adding at yc.length - 1 as the further digits of xc can be left as they are.
for (k = 0; e > 0; xc[e] %= 10) {
k = (xc[--e] = xc[e] + yc[e] + k) ~/ 10 | 0;
}
// No need to check for zero, as +x + +y != 0 && -x + -y != 0
if (k != 0) {
unShift(xc, k);
++ye;
}
// Remove trailing zeros.
for (e = xc.length; xc[--e] == 0;) {
xc.removeLast();
}
yBig.c = xc;
yBig.e = ye;
return yBig;
}