372. Super Pow

来源:互联网 发布:漳州网络诈骗举报平台 编辑:程序博客网 时间:2024/06/04 20:13

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

Credits:
Special thanks to @Stomach_ache for adding this problem and creating all test cases.

这道题需要知道公示:ab % k = (a%k)(b%k)%k

这里b是以数组的形式提供,意味着可能很长。这里采用递归的形式,递归条件是:

return (powMod(sPow(a, b, length - 1, k), 10, k) * powMod(a, b[length - 1], k)) % k;

代码如下:

public class Solution {    public int superPow(int a, int[] b) {        return sPow(a, b, b.length, 1337);    }        private int sPow(int a, int[] b, int length, int k) {        if (length == 1) {            return powMod(a, b[0], k);        }        return (powMod(sPow(a, b, length - 1, k), 10, k) * powMod(a, b[length - 1], k)) % k;    }        private int powMod(int a, int n, int k) {        a = a % k;        int result = 1;        for (int i = 0; i < n; i ++) {            result = (result * a) % k; //这里每算一步都%k对最后结果没有影响,还能防止a*a....*a*a溢出,比如9^10就会溢出。        }        return result;    }}

0 0
原创粉丝点击