一个实现长整型数相加减的小程序

//联合国科教文组织要统计人口,显然一般的int不能满足需要,因此要求定义一个BigInteger的新类,
//多写孔乙己提醒,那是我初学Java时写的,实在不该帖出来,现在重写了代码.

//时间关系,只实现了加法.

BigIntegerTest.java

/***//**
*
@authorRey
*@date2006-10-2
*/

publicclassBigIntegerTestextendsTestCase...{
publicvoidtest1()...{
BigIntegerb1
=newBigInteger("11");
BigIntegerb2
=newBigInteger("11");
BigIntegerb3
=newBigInteger("2");
assertEquals(b1,b2);
assertFalse(b1.equals(b3));
}


publicvoidtest2()...{
BigIntegerb1
=newBigInteger("12");
BigIntegerb2
=newBigInteger("8");
BigIntegerb3
=b1.add(b2);
assertEquals(
newBigInteger("20"),b3);
}


publicvoidtest3()...{
BigIntegerb1
=newBigInteger("99");
BigIntegerb2
=newBigInteger("99");
assertEquals(
newBigInteger("198"),b1.add(b2));
}


publicvoidtest4()...{
BigIntegerb1
=newBigInteger("9999999999999999");
BigIntegerb2
=newBigInteger("1");
assertEquals(
newBigInteger("10000000000000000"),b1.add(b2));
}


publicvoidtest5()...{
BigIntegerb1
=newBigInteger("1");
BigIntegerb2
=newBigInteger("9999999999999999");
assertEquals(
newBigInteger("10000000000000000"),b1.add(b2));
}

}

BigInteger.java

/***//**
*
@authorRey
*@date2006-10-2
*
*/

publicclassBigInteger...{

privateStringvalue=null;

publicBigInteger(Stringvalue)...{
this.value=value;
}


publicBigIntegeradd(BigIntegerb2)...{

char[]a=value.toCharArray();
char[]b=b2.value.toCharArray();

/***//**把最长的放到a里面*/
if(a.length<b.length)...{
char[]temp=null;
temp
=a;
a
=b;
b
=temp;
}


intsize=a.length+1;
char[]result=newchar[size];
intj=result.length-1;
/***//**把barray的值copy到result中,前面空位补48*/
for(inti=b.length-1;i>=0;i--,j--)...{
result[j]
=b[i];
}

for(;j>=0;j--)...{
result[j]
=48;
}



/***//**result=a+result*/
for(inti=a.length-1,sum=0;i>=0;i--)...{
sum
=a[i]+result[i+1];
if(sum>=106)...{
result[i
+1]=(char)(sum-10-48);
result[i]
++;
}
else...{
result[i
+1]=(char)(sum-48);
}

}


/***//**char[]转化为Stringvalue*/
StringBuffersb
=newStringBuffer();
for(inti=0;i<result.length;i++)...{
if(i==0&&(int)result[i]==48)
continue;
sb.append((
char)result[i]);
}

returnnewBigInteger(sb.toString());
}


@Override
publicinthashCode()...{
finalintPRIME=31;
intresult=1;
result
=PRIME*result+((value==null)?0:value.hashCode());
returnresult;
}


@Override
publicbooleanequals(Objectobj)...{
if(this==obj)
returntrue;
if(obj==null)
returnfalse;
if(getClass()!=obj.getClass())
returnfalse;
finalBigIntegerother=(BigInteger)obj;
if(value==null)...{
if(other.value!=null)
returnfalse;
}
elseif(!value.equals(other.value))
returnfalse;
returntrue;
}


@Override
publicStringtoString()...{
returnvalue;
}


}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值