您的位置:首页 > 其它

LeetCode-Super Pow

2016-09-12 14:04 435 查看
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 = 2
b = [3]

Result: 8

Example2:

a = 2
b = [1,0]

Result: 1024

Credits:
Special thanks to @Stomach_ache for adding this problem and creating all test cases.

Analysis:
We calculate a^1, a^10,..., and then multiply by b[i].
Solution:

public class Solution {
public int superPow(int a, int[] b) {
if (b.length==0) return -1;

int pow10 = a%1337;
int res = pow(pow10,b[b.length-1]);
for (int i=b.length-2;i>=0;i--){
pow10 = pow(pow10,10);
res = pow(pow10,b[i])*res%1337;
}
return res;
}

public int pow(int a, int b){
if (b==0){
return 1;
}

if (b==1){
return a % 1337;
}

int v1 = pow(a,b/2);
v1 = v1*v1 % 1337;
if (b%2==1) v1 = v1*(a%1337)%1337;

return v1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: