[LeetCode]372. Super Pow

来源:互联网 发布:模拟人生4作弊码mac 编辑:程序博客网 时间:2024/05/16 14:21

https://leetcode.com/problems/super-pow/#/description

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.





a ^ 123456 % 1337 = (a ^ 123450 % 1337) * (a ^ 6 % 1337) % 1337 = ((a ^ 12345) ^ 10 % 1337) * (a ^ 6 % 1337) % 1337

mod(a, b, k) = (a ^ b) % k

public class Solution {    public int superPow(int a, int[] b) {        return superPow(a, b, b.length, 1337);    }    private int superPow(int a, int[] b, int n, int k) {        if (n == 1) {            return mod(a, b[0], k);        }        return mod(superPow(a, b, n - 1, k), 10, k) * mod(a, b[n - 1], k) % k;    }    private int mod(int a, int b, int k) {        a %= k;        int res = 1;        for (int i = 0; i < b; i++) {            res = res * a % k;        }        return res;    }}


0 0
原创粉丝点击