372. Super Pow

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.

Example1:

1
2
3
4
a = 2
b = [3]
Result: 8

Example2:

1
2
3
4
a = 2
b = [1,0]
Result: 1024

解法1: 二分分割

参考了这篇解答1,主要的思想还是做二分分割。用到的性质是

1
(ab)%x = (a%x)*(b%x) % x

然后判断下是否是偶数或者奇数。这里需要记忆一个高精度除法的计算方法。

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Solution {
public static int DIV = 1337;
public void divide(int[] b, int divisor) {
int temp = 0;
for (int i = 0; i < b.length; i++) {
b[i] += temp * 10;
temp = b[i] % divisor;
b[i] /= divisor;
}
}
public boolean isZero(int[] b) {
for (int i = 0; i < b.length; i++) {
if (b[i] != 0) {
return false;
}
}
return true;
}
public int superPow(int a, int[] b) {
if (isZero(b)) {
return 1;
}
a %= Solution.DIV; // take a % first
boolean isEven = false;
if (b[b.length - 1] % 2 == 0) {
isEven = true;
}
divide(b, 2);
int sub = superPow(a, b);
sub %= Solution.DIV;
sub *= sub;
sub %= Solution.DIV;
if (!isEven) {
sub *= a;
sub %= Solution.DIV;
}
return sub;
}
}