0
点赞
收藏
分享

微信扫一扫

[leetcode] 372. Super Pow


Description

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.

Example 1:

Input:

a = 2, b = [3]

Output:

8

Example 2:

Input:

a = 2, b = [1,0]

Output:

1024

分析

题目的意思是:求a的b次方。

  • 二分法,计算结果要对1337取余。由于给定的指数b是一个一维数组的表示方法,二分法处理起来肯定十分不方便,所以采用按位来处理。
  • 比如2 的23次方 = (2的2次方)的10次方 * 2的3次方, 所以我们可以从b的最高位开始,算出个结果存入res,然后到下一位是,res的十次方再乘以a的该位次方再对1337取余

代码

class Solution {
public:
int superPow(int a, vector<int>& b) {
long long res=1;
for(int i=0;i<b.size();i++){
res=pow(res,10)*pow(a,b[i])%1337;
}
return res;
}
int pow(int x,int n){
if(n==0) return 1;
if(n==1) return x%1337;
return pow(x%1337,n/2)*pow(x%1337,n-n/2)%1337;
}
};

参考文献

​​[LeetCode] Super Pow 超级次方​​


举报

相关推荐

0 条评论