LeetCode-Super Pow

LiBlog發表於2016-09-12

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;
    }
}

 

相關文章