372. Super Pow

来源:互联网 发布:北京plc编程培训学校 编辑:程序博客网 时间:2024/06/16 02:23
class Solution(object):
    def superPow(self, a, b):
        """
        :type a: int
        :type b: List[int]
        :rtype: int
        """
        s = 1
        idx = 0
        d = {1:0}
        res = [1]
        while True:
            idx += 1
            s = (s * a) % 1337
            if s in d:
                break
            res.append(s)
            d[s] = idx
        ib = int(''.join(map(str, b)))
        idx1 = (ib - d[s]) % (idx - d[s])

        return res[d[s]+idx1]


https://discuss.leetcode.com/topic/50416/simple-python-solution-by-find-the-loop/2

思路:

1.a的所有幂次与1337取余的结果个数是有限的,所以先把结果保存到一个数组res中。然后根据幂的次数与结果周期取余得到具体幂对应的位置。

2.b为所求幂次,b可能大于结果周期,而周期开始的位置为s所在位置,所以ib-d[s]与周期长度-开始位置的余为基于s位置为起点的步长,而res数据结构是数组,所以最终结果为

res[d[s]+idx1]:

idx1是相对周期起点的长度,

d[s]是周期起点。