Big Integer Add 的简单实现

还不支持负数加(实则减)的情况。也不支持非数字字符的检测。

class Solution {
    public String add(String addend1, String addend2) {
        StringBuilder buf = new StringBuilder();
        for ( int i1 = addend1.length() - 1, i2 = addend2.length() - 1, carry = 0;
            i1 >= 0 || i2 >= 0 || carry != 0;i1--, i2-- ) {
            int digit1 = i1 < 0 ? 0 : addend1.charAt(i1) - '0';
            int digit2 = i2 < 0 ? 0 : addend2.charAt(i2) - '0';

            int digit = digit1 + digit2 + carry;
            if (digit > 9) {
                carry = 1;
                digit -= 10;
            } else {
                carry = 0;
            }

            buf.append(digit);
        }
        return buf.reverse().toString();
    }
}


本类型那样可以直接使用运算符进行操作,需要使用BigInteger类中的方法进行运算。以下是BigCalc类的实现: ```java import java.math.BigInteger; public class BigCalc { public static BigInteger add(BigInteger a, BigInteger b) { return a.add(b); } public static BigInteger subtract(BigInteger a, BigInteger b) { return a.subtract(b); } public static BigInteger multiply(BigInteger a, BigInteger b) { return a.multiply(b); } public static BigInteger divide(BigInteger a, BigInteger b) { return a.divide(b); } public static int getFactorCount(BigInteger a) { int count = 0; BigInteger i = BigInteger.valueOf(1); BigInteger limit = a.sqrt(); while (i.compareTo(limit) <= 0) { if (a.mod(i).equals(BigInteger.ZERO)) { count++; if (!i.multiply(i).equals(a)) { count++; } } i = i.add(BigInteger.ONE); } return count; } } ``` 该类中包含了加、减、乘、除四个静态方法,用于进行两个大整数的加减乘除运算。另外还包含了一个静态方法getFactorCount,用于计算一个大整数的因子个数。 以下是getFactorCount方法实现:该方法使用了BigInteger中的mod和sqrt方法,以及while循环和if语句进行计算。 ```java public static int getFactorCount(BigInteger a) { int count = 0; BigInteger i = BigInteger.valueOf(1); BigInteger limit = a.sqrt(); while (i.compareTo(limit) <= 0) { if (a.mod(i).equals(BigInteger.ZERO)) { count++; if (!i.multiply(i).equals(a)) { count++; } } i = i.add(BigInteger.ONE); } return count; } ``` 该方法首先初始化计数器count为0,然后使用BigInteger.valueOf(1)初始化i值(即从1开始逐个判断因子)。 接着,使用BigInteger的sqrt方法获取a的平方根作为循环的上限,以优化计算效率。在while循环中,使用mod方法判断i是否为a的因子,如果是,则将计数器加1。 在判断完正因子后,需要再判断负因子(即a/i是否也是a的因子),如果不是完全平方数,则将计数器再加1。 最后返回计数器的值即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值