我正在编写一个添加大数但不使用 BigInteger 的程序。不过,我有一个问题。
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;
}
因此,要添加两个数字,我使用 try-catch 两次来检查任一数组中是否还有任何数字。该方法运行良好,但这种尝试捕捉的东西看起来不太好。我可以用任何其他方式做到这一点吗?