Adding negative and positive numbers in java without BigInt.
Posted
by liamg
on Stack Overflow
See other posts from Stack Overflow
or by liamg
Published on 2010-01-21T22:49:55Z
Indexed on
2010/05/09
5:18 UTC
Read the original article
Hit count: 364
Hi, i'm trying to write a small java class. I have an object called BigNumber. I wrote method that add two positive numbers, and other method that subract two also positive numbers.
Now i want them to handle negative numbers. So the i wrote couple of 'if' statements eg.
if (this.sign == 1 /* means '+' */) {
if (sn1.sign == 1) {
if (this.compare(sn1) == -1 /* means this < sn1 */ ) return sn1.add(this);
else return this.add(sn1);
}
etc.
Unfortunately the code looks just ugly. Like a bush of if's and elses. Is there a better way to write that kind of code?
Edit
i can't just do this.add(sn1)
beacuse sometimes i want to add positive number to negative one or negitve to negative. But add can handle only positive numbers. So i have to use basic math and for example: instead of add negative number to negative number i add this.abs()
(absolute value of number) to sn1.abs()
and return the result with opposite sign. Drew: this lines are from method _add. I use this method to decide what to do with numbers it receive. Send them to add method? Or send them to subract method but with different order (sn1.subtract(this)
)? And so on..
if (this.sign == 1) {
if (sn1.sign == 1) {
if (this.compare(sn1) == -1) return sn1.add(this);
else return this.add(sn1);
}
else if (wl1.sign == 0) return this;
else {
if (this.compare(sn1.abs()) == 1) return this.subtract(sn1.abs());
else if (this.compare(sn1.abs()) == 0) return new BigNumber(0);
else return sn1.abs().subtract(this).negate(); // return the number with opposite sign;
}
} else if (this.sign == 0) return sn1;
else {
if (wl1.sign == 1) {
if (this.abs().compare(sn1) == -1) return sn1.subtract(this.abs());
else if (this.abs().compare(sn1) == 0) return new BigNumber(0);
else return this.abs().subtract(sn1).negate();
} else if (sn1.sign == 0) return this;
else return (this.abs().add(wl1.abs())).negate();
}
As you can see - this code looks horrible..
© Stack Overflow or respective owner