zoukankan      html  css  js  c++  java
  • LeetCode-Super Pow

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

    Example2:

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

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

     
     Analysis:
    We calculate a^1, a^10,..., and then multiply by b[i].
    Solution:
    public class Solution {
        public int superPow(int a, int[] b) {
            if (b.length==0) return -1;
            
            int pow10 = a%1337;
            int res = pow(pow10,b[b.length-1]);
            for (int i=b.length-2;i>=0;i--){
                pow10 = pow(pow10,10);
                res = pow(pow10,b[i])*res%1337;
            }
            return res;
        }
        
        public int pow(int a, int b){
            if (b==0){
                return 1;
            }
            
            if (b==1){
                return a % 1337;
            }
            
            int v1 = pow(a,b/2);
            v1 = v1*v1 % 1337;
            if (b%2==1) v1 = v1*(a%1337)%1337;
            
            return v1;
        }
    }
  • 相关阅读:
    JAVA周二学习总结
    2019春总结作业
    第十二周作业
    第十一周作业
    第十周作业
    第九周作业
    第八周作业
    第七周作业
    第六周作业
    第四周课程总结&试验报告(二)
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5864590.html
Copyright © 2011-2022 走看看