【LeetCode】372. Super Pow 超级次方(Medium)(JAVA)
题目地址: https://leetcode.com/problems/super-pow/
题目描述:
Your task is to calculate a^b mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array.
Example 1:
Input: a = 2, b = [3]
Output: 8
Example 2:
Input: a = 2, b = [1,0]
Output: 1024
Example 3:
Input: a = 1, b = [4,3,3,8,5,2]
Output: 1
Example 4:
Input: a = 2147483647, b = [2,0,0]
Output: 1198
Constraints:
- 1 <= a <= 2^31 - 1
- 1 <= b.length <= 2000
- 0 <= b[i] <= 9
- b doesn’t contain leading zeros.
题目大意
你的任务是计算 a^b 对 1337 取模,a 是一个正整数,b 是一个非常大的正整数且会以数组形式给出。
解题方法
- 数学原理: (a * b) % c = a % c + b % c,
- 求 a^b 可以用二分法
- 可以用循环的方式,pre = a ^ b[0] -> pre = (a ^ b[0]) ^ 10 * a ^ b[1] = pre ^ 10 * a ^ b[1] -> … -> pre = pre ^ 10 * a ^ b[n - 1]
- 最终求出结果,但是注意每一步的乘法计算都可能超出 int 上限,需要对每个结果 mod 1337
class Solution {
public int superPow(int a, int[] b) {
int pre = 1;
for (int i = 0; i < b.length; i++) {
pre = (pow(pre, 10) * pow(a, b[i])) % 1337;
}
return pre;
}
public int pow(int a, int b) {
if (a == 1 || b == 0) return 1;
if (b == 1) return a % 1337;
int half = pow(a, b / 2) % 1337;
return (half * half % 1337) * (b % 2 == 0 ? 1 : a % 1337) % 1337;
}
}
执行耗时:9 ms,击败了51.39% 的Java用户
内存消耗:38.6 MB,击败了78.59% 的Java用户