超级次方
力扣链接
题目描述
你的任务是计算 ab
对 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
提示:
1 <= a <= 231 - 1
1 <= b.length <= 2000
0 <= b[i] <= 9
b
不含前导 0
解题思路
代码(快速幂+迭代)
class Solution {
public int superPow(int a, int[] b) {
long res = 1;
int mod = 1337;
for (int i : b) {
res = mypow(res, 10, mod) * mypow(a, i, mod);
}
return (int) (res % mod);
}
long mypow(long a, long n, long mod) {
long res = 1;
while (n > 0) {
if ((n & 1) == 1) {
res = res * a % mod;
}
a = a * a % mod;
n >>= 1;
}
return res;
}
}
复杂度
-
时间复杂度:
-
空间复杂度:O(1),只需要常数的空间存放若干变量。