LeetCode刷题实战372:超级次方
Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array.
对 1337 取模,a 是一个正整数,b 是一个非常大的正整数且会以数组形式给出。示例
示例 1:
输入:a = 2, b = [3]
输出:8
示例 2:
输入:a = 2, b = [1,0]
输出:1024
示例 3:
输入:a = 1, b = [4,3,3,8,5,2]
输出:1
示例 4:
输入:a = 2147483647, b = [2,0,0]
输出:1198
解题
https://blog.csdn.net/weixin_44171872/article/details/107622115
class Solution {
public:
int my_power(int a,int c){
a%=1337;
int res=1;
for(int i=0;i<c;++i){
res*=a;
res%=1337;
}
return res;
}
int superPow(int a, vector<int>& b) {
//递归的终点
if(b.empty())
return 1;
//将原来的数组分成两部分进行计算
//第一部分
int part1=my_power(a,b.back());
b.pop_back();
//第二部分
int part2=my_power(superPow(a,b),10);
return part1*part2%1337;//将两部分之积再次求余
}
};
评论
