[LeetCode][372. Super Pow] 2 Approaches: Brute Force and Binary Exponentiation
By Long Luo
This article is the solution 2 Approaches: Brute Force and Binary Exponentiation of Problem 372. Super Pow .
Intuition
This problem is to find a integer raised to the power a very large number whose length may be \(200\) or more.
Brute Froce
We multiply \(a\) to itself \(b\) times. That is, \(a^b = \underbrace{a \times a \dots \times a}_b\) .
We can write such code easily.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17public static int superPow(int a, int[] b) {
if (a == 1) {
return 1;
}
int ans = a;
int len = b.length;
for (int i = len - 1; i >= 0; i--) {
int base = (int) Math.pow(10, len - 1 - i);
int num = b[i] * base;
for (int j = 1; j < num; j++) {
ans = ((ans % 1337) * (a % 1337)) % 1337;
}
}
return ans;
}
Analysis
- Time Complexity: \(O(10^mb_i)\) , \(m\) is the length of array b.
- Space Complexity: \(O(1)\)
Obiviously, it will exceed time limit, so we have to find a more efficiently algorithm.