Java sol using Math equation and extension of Pow() sol


  • 0
    C
            private static final int MOD = 1337;
    
    	// we are going to use the formula
    	// xy mod z = (x mod z) * (y mod z) * mod z
    	public int superPow(int a, int[] b) {
    		if (a == 1) {
    			return 1;
    		}
            
                    a = a%MOD;
    
    		int len = 0, result = 1;
    		while (len < b.length) {
                            // adding base 10 the prev result which represents x and taking the a^b[i] which represents y
    			result = (pow(result, 10) * pow(a, b[len++])) % MOD;
    		}
    
    		return result;
    	}
    
    	// this is same as find Pow problem.
    	private int pow(int a, int b) {
    		if (b == 1) {
    			return a;
    		}
    
    		if (b == 0) {
    			return 1;
    		}
    
    		int val = pow(a, b/2);
    		int result = (val * val) % MOD;
    
    		if (b % 2 == 0) {
    			return result;
    		}
    
    		return (result * a) % MOD;
    	}
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.