1 题目描述
来源:力扣(LeetCode)
实现函数double Power(double base, int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。
2 解题思路
- 快速幂法(二进制角度)1
- 快速幂法(二分法角度)
3 代码实现(Python3)
class Solution:
def myPow(self, x: float, n: int) -> float:
if x == 0: return 0
res = 1
if n < 0: x, n = 1 / x, -n
while n:
if n & 1: res *= x
x *= x
n >>= 1
return res
4 复杂度分析
- 时间复杂度 O(log 2 n) : 二分的时间复杂度为对数级别。
- 空间复杂度 O(1) : res, b 等变量占用常数大小额外空间。
深入了解复杂度:数据分析学习总结笔记11:空间复杂度和时间复杂度