解决大数值问题

[size=medium]public class TestBigInteger {
public static void main(String[] args) {
BigInteger i = new BigInteger(1);
for (int n = 2; n <= 1000; n++) {
i.multiply(n);
}
System.out.println(i);
System.out.println(i.toString().length());
}
}

// 自定义的 BigInteger class BigInteger {
// 初始化数组。每个元素可以包含 9 位数字,所以初始化有 90 位
private int ints[] = new int[10];
// 达到或超过这个值就进位
private static final int UPPER_BOUND = 1000000000;
public BigInteger(int value) {
ints[0] = value;
}
public BigInteger(BigInteger value) {
ints = Arrays.copyOf(value.ints, value.ints.length);
}
public void multiply(int n) {
BigInteger that = new BigInteger(this);
for (int i = 0; i < n - 1; i++) {
add(that);
}
}
private void add(BigInteger bigInteger) {
int[] ints2 = bigInteger.ints;
for (int i = 0; i < ints2.length; i++) {
ints[i] += ints2[i]; checkAndCarry(i);
}
checkAndIncrease(); } // 检查指定位置的值。有必要的话就进位。
private void checkAndCarry(int i) {
if (ints[i] >= UPPER_BOUND && i < ints.length - 1) {
ints[i] -= UPPER_BOUND; ints[i + 1]++;
}
}
// 检查最后一个元素的值。达到或超过进位大小则增加数组长度。
private void checkAndIncrease() { if (ints[ints.length - 1] > UPPER_BOUND) {
int[] newints = Arrays.copyOf(ints, ints.length + 1);
newints[ints.length - 1] -= UPPER_BOUND; newints[ints.length]++;
ints = newints;
}
}
@Override public String toString() {
DecimalFormat f = new DecimalFormat("000000000");
StringBuffer sb = new StringBuffer();
for (int each : ints) {
sb.insert(0, f.format(each));
}
while (sb.charAt(0) == '0') {
sb.delete(0, 1);
}
return sb.toString();
}
}

[/size]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值