leetcodeOJ 372. Super Pow

来源:互联网 发布:mysql update into 编辑:程序博客网 时间:2024/06/03 13:17

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 = 2b = [3]Result: 8

Example2:

a = 2b = [1,0]Result: 1024

思路:

基础知识:a*b % k = (a%k) * (b%k) %k
扩展:a^1234567 % k = (a^1234560 % k) * (a^7 % k) % k = (a^123456 % k)^10 % k * (a^7 % k) % k

代码如下:

class Solution {public:    int superPow(int a, vector<int>& b) {        if(b.size() == 0){            return 1;        }        int lastNum = b.back();        b.pop_back();        return pow(superPow(a, b), 10) * pow(a, lastNum) % 1337;    }    private:    int pow(int a, int last){        a %= 1337;        int ans = 1;        for(int i = 0; i < last; i++){            ans *= a;            ans %= 1337;        }        return ans;    }};

0 0
原创粉丝点击