您的位置:首页 > 其它

leetcode Super Pow

2016-07-24 20:46 351 查看
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.

这题是真没想出来,看解法思路是这样的,首先需要了解一个数学理论:

(a*b)%c=(a%c)*(b%c),由于这道题会出现溢出情况,所以这个理论会经常使用。

再有就是求n次方的问题,递归根据奇偶数讨论即可:

public int superPow(int a, int[] b) {
if(isZero(b)) return 1;
a=a%1337;
boolean isOdd=true;
if(b[b.length-1]%2==0) isOdd=false;
divide(b,2);
int res=superPow(a,b);
res=res%1337;
res*=res;
res=res%1337;
if(isOdd){
res=(res*a)%1337;
}
return res;
}
public void divide(int[] b,int a){
int temp=0;
for(int i=0;i<b.length;i++){
b[i]+=temp*10;
temp=b[i]%a;
b[i]/=a;
}
}
public boolean isZero(int[] a){
for(int i=a.length-1;i>=0;i--){
if(a[i]!=0) return false;
}
return true;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法