Advertisement
1988coder

372. Super Pow

Jan 19th, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.11 KB | None | 0 0
  1. // LeetCode URL: https://leetcode.com/problems/super-pow/
  2. /**
  3.  * a ^ (5236) = ( ( (a^5)^10 * a^2)^10 * a^3)^10 * a^6
  4.  *
  5.  * (a*b) % k = ( (a%k) * (b%k) ) % k
  6.  *
  7.  * Time Complexity: O(N * 2 * log 10) = O(N). getPow is recursivly called
  8.  * maximum 4 times.
  9.  *
  10.  * Space Complexity: O(log 10) = O(1). getPow recursion stack will maximum be of
  11.  * size 4. As each number in array b is a single digit.
  12.  */
  13. class Solution {
  14.  
  15.     int DIV = 1337;
  16.  
  17.     public int superPow(int a, int[] b) {
  18.         a = a % DIV;
  19.         if (a == 0 || b == null) {
  20.             return 0;
  21.         }
  22.         if (a == 1 || b.length == 0) {
  23.             return a;
  24.         }
  25.  
  26.         int result = 1;
  27.  
  28.         for (int i = 0; i < b.length; i++) {
  29.             result = getPow(result, 10) * getPow(a, b[i]) % DIV;
  30.         }
  31.  
  32.         return result;
  33.     }
  34.  
  35.     private int getPow(int a, int b) {
  36.         if (a == 1 || b == 0) {
  37.             return 1;
  38.         }
  39.         if (a == 0 || b == 1) {
  40.             return a;
  41.         }
  42.  
  43.         int res = getPow(a * a % DIV, b / 2);
  44.  
  45.         return b % 2 == 0 ? res : a * res % DIV;
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement