leetcode 372. Super Power

@(labuladong's algorithm cheat sheet) [Mathematics]

leetcode 372. Super Power

Title description

Insert picture description here

Problem-solving ideas

Reference: labuladong's algorithm cheat sheet P355

class Solution {
    
    
    private int base = 1337;
    public int superPow(int a, int[] b) {
    
    
        LinkedList<Integer> listOfB = new LinkedList<>();
        for (int n : b)
            listOfB.add(n);
        return helper(a, listOfB);
    }

    private int helper(int a, LinkedList<Integer> listOfB) {
    
    
        /* base case */
        if (listOfB.isEmpty()) return 1;
        /* 取出最后一个数 */
        Integer last = listOfB.removeLast();
        /* 将原问题化简,缩小规模递归求解 */
        int part1 = quickPow(a, last);
        int part2 = quickPow(helper(a, listOfB), 10);
        return (part1 * part2) % base;
    }
    /* 快速幂 */
    public long quickPow(long base, int exponent) {
    
    
        if (exponent == 0) return 1;
        if (exponent == 1) return base;

        long res = quickPow(base, exponent >> 1);
        res = (res * res) % mod;
        //如果是奇数,则要额外乘上base
        if ((exponent & 0x01) == 1)
            res = (res * base) % mod;
        return res;
    }
}

Guess you like

Origin blog.csdn.net/cys975900334/article/details/114693363