其他分享
首页 > 其他分享> > 剑指 Offer 14- II. 剪绳子 II——大数求余(循环求余、快速幂法)

剑指 Offer 14- II. 剪绳子 II——大数求余(循环求余、快速幂法)

作者:互联网

剑指 Offer 14- II. 剪绳子 II

题目

在这里插入图片描述

题解:

首先根据数学的结论得出每段的长度是3的时候是最优的解。详细的推到见https://leetcode-cn.com/problems/jian-sheng-zi-lcof/solution/mian-shi-ti-14-i-jian-sheng-zi-tan-xin-si-xiang-by/

循环求余法

class Solution {
    public int cuttingRope(int n) {
        //数学方法
        //推论:1.当每段等长的时候,乘积的积是最大的
        //推论:2.每段的长度是3的时候是最大的
        int p=1000000007;
        if(n<4) 
            return n-1;
        else if(n==4)
            return n;
        long res=1;
        while(n>4){
            res*=3;
            res%=p;
            n-=3;
        }
        //最终剩下2.3.4刚好对应余数为0.1.2的情况
        return (int)(res*n%p);
    }
}

快速幂求余

重写了Math.pow()的方法,在计算的过程中就直接求余。

class Solution {
    int mod = 1000000007;
    public int cuttingRope(int n) {
        if(n < 4) return n - 1;
        int a = n / 3;
        int b = n % 3;
        if(b == 0) return (int) (myPow(3, a) % mod);
        else if(b == 1) return (int) (myPow(3, a - 1) * 4 % mod);
        else return (int) (myPow(3, a) * 2 % mod);
    }

    public long myPow(long base, int num){
        long res = 1;
        while(num > 0){
            if((num & 1) == 1){
                res *= base;
                res %= mod;
            }
            base *= base;
            base %= mod;
            num >>= 1;
        }
        return res;
    }
}

标签:return,14,int,res,num,II,base,求余,mod
来源: https://blog.csdn.net/shooter7/article/details/119270073