leetcode 372. Super Pow

你的任务是计算 ab 对 1337 取模,a 是一个正整数,b 是一个非常大的正整数且会以数组形式给出。
(a ^ b)mod c = (a mod c)^b mod c

示例 1:

输入: a = 2, b = [3]
输出: 8
示例 2:

输入: a = 2, b = [1,0]
输出: 1024

方法一

class Solution1 (object):
    def superPow(self, a, b):
        """
        :type a: int
        :type b: List[int]
        :rtype: int
        """
        b = int (''.join (map(str,b)))
        a = a % 1337
        return self.helper (a, b)

    def helper(self, a, b):
        if a == 0: return 0
        if a == 1: return 1
        if b == 1: return a % 1337
        if b % 2 == 0:
            coco = self.helper(a, b // 2)
            return (coco * coco) % 1337
        if b % 2 == 1:
            coco = self.helper(a, b // 2)
            return (coco * coco * a) % 1337

方法二

class Solution:
    def superPow(self, a, b):
        """
        :type a: int
        :type b: List[int]
        :rtype: int
        """
        from functools import reduce
        print(reduce(lambda x, y: (x * 10 + y) % 1140, b))

        return 0 if a % 1337 == 0 else pow(a, reduce(lambda x, y: (x * 10 + y) % 1140, b) + 1140, 1337)

S = Solution()
res = S.superPow(2,[1,2,3,4])
print(res)

结果如下:

93
956
原文地址:https://www.cnblogs.com/nxf-rabbit75/p/9804916.html