Super Pow

来源:互联网 发布:淘宝实体微商女装货源 编辑:程序博客网 时间:2024/04/30 19:58

Your task is to calculate ab mod 1337 where a is a positive integer andb 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%c, 计算的时候,在任何时候%c都可以;因为是乘法运算

这道题和之前那道Pow(x, n)的解法很类似,我们都得对半缩小,不同的是后面都要加上对1337取余。由于给定的指数b是一个一维数组的表示方法,我们要是折半缩小处理起来肯定十分不方便,所以我们采用按位来处理,比如223 = (22)10 * 23, 所以我们可以从b的最高位开始,算出个结果存入res,然后到下一位是,res的十次方再乘以a的该位次方再对1337取余。举个例子223 = (22)10 * 23,:就是前面位数累积到下一位进行计算的时候,res需要pow(res,10)。这个是解题关键。

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


0 0
原创粉丝点击