Skip to content

372. Super Pow

Difficulty: Medium

LeetCode Problem View on GitHub


372. Super Pow

Medium


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.

 

Example 1:

Input: a = 2, b = [3]
Output: 8

Example 2:

Input: a = 2, b = [1,0]
Output: 1024

Example 3:

Input: a = 1, b = [4,3,3,8,5,2]
Output: 1

 

Constraints:

  • 1 <= a <= 231 - 1
  • 1 <= b.length <= 2000
  • 0 <= b[i] <= 9
  • b does not contain leading zeros.

Solution

class Solution {
    static int mod = (int)(1337);
    public int superPow(int a, int[] b) {
        long res = 1;
        for (int i = b.length - 1; i >= 0; i--) {
            res = mul(res, fast_pow(a, b[i], mod));
            a = (int)(fast_pow(a, 10, mod));
        }
        return (int)(res);
    }
    static long fast_pow(long a, long p, long mod) {
        long res = 1;
        while (p > 0) {
            if (p % 2 == 0) {
                a = ((a % mod) * (a % mod)) % mod;
                p /= 2;
            }
            else {
                res = ((res % mod) * (a % mod)) % mod;
                p--;
            }
        }
        return res;
    }
    static long mul(long a, long b) {return (long) ((long) ((a % mod) * 1L * (b % mod)) % mod);}
}

Complexity Analysis

  • Time Complexity: O(?)
  • Space Complexity: O(?)

Approach

Detailed explanation of the approach will be added here