实现 pow(x, n) ,即计算 x 的 n 次幂函数。
示例 1:
输入: 2.00000, 10
输出: 1024.00000
示例 2:
输入: 2.10000, 3
输出: 9.26100
示例 3:
输入: 2.00000, -2
输出: 0.25000
解释: 2-2 = 1/22 = 1/4 = 0.25
说明:
-100.0 < x < 100.0
n 是 32 位有符号整数,其数值范围是 [−231, 231 − 1] 。
思路:快速幂,没什么好说的,唯一我没想到的(也是致命的)就是,对于负数次幂,只要反过来x就可以解决问题哈哈哈,我还为负数幂魔改了半天快速幂,怎么也搞不对。
class Solution {public double myPow(double x, int n) {long N = n;if (N < 0) {x = 1 / x;N = -N;}double ans = 1;double current_product = x;for (long i = N; i > 0; i /= 2) {if ((i % 2) == 1) {ans = ans * current_product;}current_product = current_product * current_product;}return ans;}
}