Python 中的 Pow(x, n)

pythonserver side programmingprogramming更新于 2025/10/25 18:52:17

假设我们有两个输入 x 和 n。x 是 -100.0 到 100.0 范围内的数字,n 是 32 位有符号整数。我们必须在不使用库函数的情况下找到 x 的 n 次方。

因此,如果给定的输入是 x = 12.1,n = -2,则输出将为 0.00683

为了解决这个问题,我们将遵循以下步骤 −

  • power := |n|并且 res := 1.0
  • 当 power 不为 0 时
    • 如果 power 的最后一位为 1,则 res := res * x
    • x := x * x
  • 如果 n < 0
    • 返回 1 / res
  • 返回 res

示例 (Python)

让我们看下面的实现,以便更好地理解 −

class Solution(object):
   def myPow(self, x, n):
      power = abs(n)
      res = 1.0
      while power:
         if power & 1:
            res*=x
         x*=x
         power>>=1
      if n<0:
         return 1/res
      return res
ob1 = Solution()
print(ob1.myPow(45, -2))
print(ob1.myPow(21, 3))

输入

45
-2
21
3

输出

0.0004938271604938272
9261.0

相关文章


有用资源