@(labuladong的算法小抄)[数学]
leetcode 372. 超级次方
题目描述
解题思路
参考:labuladong的算法小抄P355
class Solution {
private int base = 1337;
public int superPow(int a, int[] b) {
LinkedList<Integer> listOfB = new LinkedList<>();
for (int n : b)
listOfB.add(n);
return helper(a, listOfB);
}
private int helper(int a, LinkedList<Integer> listOfB) {
/* base case */
if (listOfB.isEmpty()) return 1;
/* 取出最后一个数 */
Integer last = listOfB.removeLast();
/* 将原问题化简,缩小规模递归求解 */
int part1 = quickPow(a, last);
int part2 = quickPow(helper(a, listOfB), 10);
return (part1 * part2) % base;
}
/* 快速幂 */
public long quickPow(long base, int exponent) {
if (exponent == 0) return 1;
if (exponent == 1) return base;
long res = quickPow(base, exponent >> 1);
res = (res * res) % mod;
//如果是奇数,则要额外乘上base
if ((exponent & 0x01) == 1)
res = (res * base) % mod;
return res;
}
}