I’m writing a program for addding large numbers but without using BigInteger. I have a problem in long addition though.
int l = this.arr.length > arg.arr.length ? this.arr.length : arg.arr.length;
byte[] result = new byte[l];
byte carry = 0;
for(int i = 0; i < result.length; i++){
byte sum;
try{
sum = (byte) (this.arr[i] + arg.arr[i] + carry);
}
catch(ArrayIndexOutOfBoundsException e){
try{
sum = (byte) (this.arr[i] + carry);
}
catch(ArrayIndexOutOfBoundsException ex){
sum = (byte) (arg.arr[i] + carry);
}
}
//carry
if(sum > 9){
result[i] = (byte) (sum % 10);
carry = 1;
}
else{
result[i] = sum;
carry = 0;
}
}
if(carry > 0){
byte[] tmp = new byte[l+1];
System.arraycopy(result, 0, tmp, 0, l);
tmp[tmp.length - 1] = carry;
result = tmp;
}
So to add two numbers I’m using try-catch twice to check whether there are any digits left in either of arrays. The method’s working fine but this try-catch thing doesn’t look so nice. Could I do this in any other way?
Use an
ifstatement to check thatiis<this.arr.length.