Python中的Pow(x, n)

假设我们有两个输入x和n。x是一个介于-100.0到100.0之间的数字,并且n是一个32位有符号整数。我们必须不使用库函数而将x乘以n。

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

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

  • 幂:= | n | 和res:= 1.0

  • 当幂不为0时

    • 如果电源的最后一位是1,则res:= res * x

    • x:= x * x

  • 如果n <0

    • 返回1 / 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