https://leetcode.com/problems/powx-n/
快速幂的实现!


分治,有递归和迭代的处理,写起来要熟练!

递归

  1. class Solution:
  2. def myPow(self, x: float, n: int) -> float:
  3. if n == 0:
  4. return 1
  5. isNeg = n < 0
  6. n = -n if isNeg else n
  7. half = self.myPow(x, n // 2)
  8. res = half * half
  9. if n % 2 == 1:
  10. res *= x
  11. return 1 / res if isNeg else res

迭代

  1. class Solution:
  2. def myPow(self, x: float, n: int) -> float:
  3. isNeg = n < 0
  4. n = -n if isNeg else n
  5. res = 1.
  6. while n > 0:
  7. if n % 2 == 1:
  8. res *= x
  9. x *= x
  10. n //= 2
  11. return 1. / res if isNeg else res