[leetcode] 372. Super Pow

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

需用到的数学知识:

a^b % 1337 = (a%1337)^b % 1337

xy % 1337 = ((x%1337) * (y%1337)) % 1337

例如:

X^678 = ((X^670 % 1337) * (X^8 % 1337)) % 1337 = (superPow((X^67 % 1337), 10) * (X^8 % 1337)) % 1337

java代码实现:

public class Solution_372 {

    public int superPow(int a, int k) {
        if (k == 0) return 1;
        int ans = 1;
        for (int i = 1; i <= k; i++)
            ans = (ans * a) % 1337;
        return ans;
    }

    public int superPow(int a, int[] b) {
        if (b.length == 0)
            return 1;
        a = a % 1337;
        int lastBit = b[b.length - 1];
        int[] newB = new int[b.length - 1];
        for (int i = 0; i < b.length - 1; i++) {
            newB[i] = b[i];
        }
        return (superPow(superPow(a, newB), 10) * superPow(a, lastBit)) % 1337;
    }

}

猜你喜欢

转载自blog.csdn.net/qq_27437197/article/details/86720491
今日推荐