快速幂
快速幂,二进制取幂(Binary Exponentiation,也称平方法),是在一个$O(\lg n)$的时间内计算$a^n$的小技巧,而暴力计算需要$O(n)$的时间。
LC50. Pow(x, n) 实现乘方函数,底数为double,指数为32-bit signed integer
方法一:递归实现
class Solution { public: double myPow(double x, int n) { long m = n; if (m == 0) return 1; if (m < 0) { m = -m; x = 1 / x; } return m % 2 != 0 ? x * myPow(x * x, m / 2) : myPow(x * x, m / 2); } };
方法二:迭代实现,实际中迭代更快
class Solution { public: double myPow(double x, int n) { long m = n; if (m == 0) return 1; if (m < 0) { m = -m; x = 1 / x; } double res = 1; while (m) { if (m & 1) res *= x; x = x * x; m >>= 1; } return res; } };