题目链接:https://leetcode-cn.com/problems/shu-zhi-de-zheng-shu-ci-fang-lcof/
难度:中等

描述:
实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,xn)。不得使用库函数,同时不需要考虑大数问题。

题解

  1. class Solution:
  2. def myPow(self, x: float, n: int) -> float:
  3. if x == 0:
  4. return 0
  5. if n < 0:
  6. x, n = 1 / x, -n
  7. ret = 1
  8. while n > 0:
  9. # n为奇数
  10. if n & 1 == 1:
  11. ret *= x
  12. x *= x
  13. n >>= 1
  14. return ret