LeetCode 题解工作台

超级次方

你的任务是计算 a b 对 1337 取模, a 是一个正整数, b 是一个非常大的正整数且会以数组形式给出。 示例 1: 输入: a = 2, b = [3] 输出: 8 示例 2: 输入: a = 2, b = [1,0] 输出: 1024 示例 3: 输入: a = 1, b = [4,3,3…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 数学·结合·divide·conquer

bolt

答案摘要

我们初始化答案变量 $ans = 1$。 接下来,倒序遍历数组 ,每次遍历到一个元素 ,我们将答案变量 自乘 并对 取模,然后将 自乘 次并对 取模。这里需要用到快速幂。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数学·结合·divide·conquer 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

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

 

示例 1:

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

示例 2:

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

示例 3:

输入:a = 1, b = [4,3,3,8,5,2]
输出:1

示例 4:

输入:a = 2147483647, b = [2,0,0]
输出:1198

 

提示:

  • 1 <= a <= 231 - 1
  • 1 <= b.length <= 2000
  • 0 <= b[i] <= 9
  • b 不含前导 0
lightbulb

解题思路

方法一:快速幂

我们初始化答案变量 ans=1ans = 1

接下来,倒序遍历数组 bb,每次遍历到一个元素 ee,我们将答案变量 ansans 自乘 aea^e 并对 13371337 取模,然后将 aa 自乘 1010 次并对 13371337 取模。这里需要用到快速幂。

遍历完数组后,返回答案即可。

时间复杂度 O(i=0n1logbi)O(\sum_{i=0}^{n-1} \log b_i),空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
class Solution:
    def superPow(self, a: int, b: List[int]) -> int:
        mod = 1337
        ans = 1
        for e in b[::-1]:
            ans = ans * pow(a, e, mod) % mod
            a = pow(a, 10, mod)
        return ans
speed

复杂度分析

指标
时间complexity depends on the length of b; each recursive step reduces b by one digit, and modular exponentiation takes constant time per step, yielding roughly O(n log a) time. Space complexity is O(n) due to recursion stack proportional to b's length.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Expect you to recognize that direct exponentiation will overflow for large b arrays.

  • question_mark

    Interviewers want to see divide-and-conquer applied to array-based exponentiation with modulo optimization.

  • question_mark

    Clarifying edge cases for a = 1 or b = [0] can demonstrate thorough understanding.

warning

常见陷阱

外企场景
  • error

    Attempting direct calculation of a^b without modular reduction causes overflow.

  • error

    Ignoring the array nature of b leads to miscalculating large exponents.

  • error

    Forgetting to apply modulo 1337 at each step produces incorrect results.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Compute a^b mod m for different modulus values, adjusting recursive multiplication accordingly.

  • arrow_right_alt

    Handle exponents given in string format rather than array digits.

  • arrow_right_alt

    Support negative base values with proper modular handling.

help

常见问题

外企场景

超级次方题解:数学·结合·divide·conquer | LeetCode #372 中等