372. Super Pow

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution {
private static final int BASE = 1337;

public int superPow(int a, int[] b) {
return superPow(a, b, b.length - 1);
}

private int superPow(int a, int[] b, int endIndex) {
if (endIndex == -1) { // 注意此处是 -1, 0 是需要计算的
return 1;
}

int power = b[endIndex];
return quickPow(superPow(a, b, endIndex - 1), 10) * quickPow(a, b[endIndex]) % BASE;
}

private int quickPow(int a, int b) {
if (b == 0) {
return 1;
}

// 注意可能越界的地方都要进行求余
a %= BASE;

int res = 1;
while (b > 0) {
if ((b & 1) == 1) {
res = res * a % BASE;
}

a = a * a % BASE;
b >>= 1;
}

return res;
}
}

References

372. Super Pow