LeetCode——372. Super Pow

时间:2024-01-21 11:54:33

题目链接:https://leetcode.com/problems/super-pow/description/

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:

a =
b = [] Result:

Example2:

a =
b = [,] Result:

计算一个a的b次幂,然后对1337取模。

刚开始没注意取模直接看Example就写了程序:

static int superPow(int a, int[] b) {
int sub = 1,mod = 0,ex = 1;
for(int i = b.length - 1; i >= 0; i--){
mod += (b[i] * ex);
ex *= 10;
}
System.out.println(mod);
for(;mod > 0; mod--){
sub = sub * a;
}
return sub;
}

本来以为直接对结果取模就行,但其实是会出现很大的问题的,因为题目说了这个a将是一个很大的数字,假如a的b次幂大于int的范围就会出错,所以不能在最后的结果取模。

用到的数学公式:a ^ b % p = ((a % p)^b) % p

所以第二次修改就是:

static int superPow(int a, int[] b) {
int sub = 1,mod = 0,ex = 1;
for(int i = b.length - 1; i >= 0; i--){
mod += (b[i] * ex);
ex *= 10;
}
a = a%1337;
System.out.println(mod);
for(;mod > 0; mod--){
sub = sub * a;
}
return sub%1337;
}

这里一开始就对a进行了取模运算,然后在求幂,最后再进行一次取模运算,得到结果。

然后还有问题,就是在求幂的时候也会超出范围。所以在求幂的时候也要注意不要超出范围。

这次用到的公式就是:(a * b) % p = (a % p * b % p) % p

所以第三次修改就是:

static int superPow(int a, int[] b) {
int sub = 1,mod = 0,ex = 1;
for(int i = b.length - 1; i >= 0; i--){
mod += (b[i] * ex);
ex *= 10;
}
a = a%1337;
System.out.println(mod);
for(;mod > 0; mod--){
sub = sub%1337 * a;
}
return sub%1337;
}

到目前为止幂的运算一直都没问题,一直忽略了b数组的读取,万一b数组代表的数是大于int的范围也同样会出错。

这里使用的公式大体就是:

a^123 = (a^3)^1*(a^2)^10*(a^1)^100;

class Solution {
public int superPow(int a, int[] b) {
int sub = 1, j = 1;
for(int i = b.length - 1; i >= 0; i--) {
sub *=(Pow(Pow(a, b[i]), j))%1337;
j *= 10;
}
return sub%1337;
}
int Pow(int a, int k) {
int sub = 1;
if(k == 0) return 1;
a = a%1337;
for(;k > 0; k--){
sub = (sub %1337) * a;
}
return sub%1337;
}
}