剑指 Offer 14- II. 剪绳子 II(数学+快速幂求余)
作者:互联网
// 快算幂计算过程中使用long long, 避免int溢出
long long myPow(long long base, long long p, int mod)
{
long long ret = 1;
while(p)
{
if(p&1)
{
ret = ret * base % mod;
}
p = p>>1;
base = base*base % mod;
}
return ret;//返回值小于mod
}
int cuttingRope(int n){
if(n<=3) return n-1;
int mod = 1000000007;
int residue = n%3;
int count = n/3;
// 返回最终结果前取余
if(residue == 2) return myPow(3, count, mod)*2%mod;
else if(residue == 1) return myPow(3, count-1, mod)*4%mod;
else return myPow(3, count, mod);
}
标签:14,幂求,int,long,II,base,ret,mod 来源: https://blog.csdn.net/jayloncheng/article/details/120106047