大数算法(大数相加)

这几天做projecteuler
发现数学很重要啊!
当计算非常大的数的相乘时,使用BigDecimal
便希望能自己实现大数的乘法
因为乘法里要使用加法,就先实现加法了
开始时,大数使用字符串保存
这时候我们需要将大数存储在一个数组里
为了节省空间,我们使用Byte存储每一位

	public static Byte[] StringToByte(String number){
    
int len = number.length();
Byte[] result = new Byte[len];
//从高位到低位依次转换,转换后字符串"1234"变为4321,这样方便以后计算
for(int i=0; i byte curByte = Integer.valueOf(number.charAt(i)+"").byteValue();
result[len-i-1] = curByte;
}

return result;
}


加法算法

	public static Byte[] Add(Byte[] number1, Byte[] number2){
    
int len = (number1.length>number2.length) ? number1.length : number2.length;
Byte[] result = new Byte[len+1];
Integer sum = new Integer(0);
Integer carry = new Integer(0);
int i;
if(number1.length>number2.length){
for(i=0; i sum = number1[i].intValue() + number2[i].intValue();
sum = sum +carry;
carry = ((sum -10)>=0) ? 1:0;
sum = ((sum -10)>=0) ? (sum-10):sum;
result[i] = sum.byteValue();
sum = 0;
}
for(;i sum = sum +carry;
carry = ((sum -10)>=0) ? 1:0;
sum = ((sum -10)>=0) ? (sum-10):sum;
result[i] = sum.byteValue();
sum = 0;
}
if(carry!=0){
result[i] = carry.byteValue();
}else{
result[i] = 0;
}
}else{
for(i=0; i sum = number1[i].intValue() + number2[i].intValue();
sum = sum +carry;
carry = ((sum -10)>=0) ? 1:0;
sum = ((sum -10)>=0) ? (sum-10):sum;
result[i] = sum.byteValue();
sum = 0;
}
for(;i sum = number2[i].intValue() + carry;
carry = ((sum -10)>=0) ? 1:0;
sum = ((sum -10)>=0) ? (sum-10):sum;
result[i] = sum.byteValue();
sum = 0;
}
if(carry!=0){
result[i] = carry.byteValue();
}else{
result[i] = 0;
}
}

return result;
}

你可能感兴趣的:(Java网络编程,算法)