亚马逊面试题:实现 pow(x, n) 函数——快速幂算法详解

37次阅读
没有评论

Implement the function pow(x, n), which calculates x^n.
Note that you cannot use any built-in functions that directly implement pow.

Examples:

  • Input: x = 2, n = 5 → Output: 32
  • Input: x = 3.4, n = 3 → Output: 39.04

  • 朴素方法是循环乘 n 次,时间复杂度为 O(n)
  • 高效方法是使用 二分幂(快速幂),将时间复杂度降为 O(log n)
  • 当指数为负时,返回 1 / pow(x, -n)
  • 注意边界条件:x = 0n = 0n < 0 等。

VOprep 团队长期陪同学员实战各类大厂 OA 与 VO,包括 Google、Amazon、Citadel、SIG 等,提供实时答案助攻、远程陪练与面试节奏提醒,帮助大家在关键时刻不卡壳。
如果你也在准备公司,可以了解一下我们的定制助攻方案——从编程面到系统设计,全程护航上岸。

正文完
 0