力扣 面試題14- II. 剪繩子 II 快速冪+貪心

https://leetcode-cn.com/problems/jian-sheng-zi-ii-lcof/submissions/
在這裏插入圖片描述

思路:指數爆炸,取33爲底。

class Solution {
public:
    const int mod=1e9+7;
    using ll=long long;
    ll qpow(int a,int b)
    {
        ll t1=1,t2=a;
        while(b)
        {
            if(b&1)
                t1=t1*t2%mod;
            t2=t2*t2%mod;
            b>>=1;
        }
        return t1;
    }

    int cuttingRope(int n) {
        if(n<=3)
            return n-1;
        int res=n%3;
        if(res==1)
            return qpow(3,n/3-1)*4%mod;
        if(!res)
            res=1;
        return qpow(3,n/3)*res%mod;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章