TypechoJoeTheme

Toasobi的博客

剪绳子2(中等)

本文最后更新于2023年03月07日,已超过562天没有更新。如果文章内容或图片资源失效,请留言反馈,我会及时处理,谢谢!

这道题和上一道的区别是:使用取模前的数字进行比较,输出结果要取模。因为有取模环节。其次这题数字很大,属于大数考察

一开始做这题的时候想用int,发现必超内存,于是就想使用long,但是由于需要使用pow函数,该函数返回值是double,double强转long会丢失精度,会导致解题错误,于是最终妥协使用了BigInteger

要注意BigInteger的使用,里面的取幂,乘积,比较等等都是需要该类下的指定函数的。下面是代码:

<div>
import java.math.BigInteger;
class Solution {
    public int cuttingRope(int n) {
        BigInteger max = BigInteger.valueOf(0);
        //long max = 0;
        int s = (int)Math.sqrt(n);
        if(n == 1 || n ==2)
            return 1;
        if(n == 3)
            return 2;
        
        for(int i=2;i<=n;i++){ //m表示几段
            BigInteger temp = BigInteger.valueOf(1);
            //long temp = 1;
            int a,b = 0; //除数,余数
            a = n/i; //除数
            b = n%i; //余数
                    
            temp = BigInteger.valueOf(a+1).pow(b);
            temp = temp.multiply(BigInteger.valueOf(a).pow(i-b));
            if(temp.compareTo(max) > 0)
                max = temp;
        }
        return (max.mod(BigInteger.valueOf(1000000007))).intValue();
    }
}
</div>

======================

  • 方法二:贪心算法

======================

这道题和上道一样还是可以使用贪心,具体步骤也是差不多的
只不过这里要循环取余保证它不会超过int的大小
代码如下:

<div>
class Solution {
    public int cuttingRope(int n) {
        if(n == 2)
            return 1;
        if(n == 3)
            return 2;
        long res = 1;
        while(n > 4){
            res *= 3;
            res = res % 1000000007;
            n -= 3;
        }
        return (int)(res * n % 1000000007);
    }
}
</div>
朗读
赞(0)
评论 (0)