Pow(x, n)

题目

Implement pow(x, n).


Example 1:

Input: 2.00000, 10
Output: 1024.00000

Example 2:

Input: 2.10000, 3
Output: 9.26100

分析

1. 题目要求

给出一个实数 x和一个整数n,求x的n次方。

2. 求解思路

对于求解一个数的n次方问题,一般使用二分法来求解。

例如,求解 15 的8次方。

15^8 = (15^4) * (15 ^4);

15^4 = (15^2) * (15^2);

15^2 = 15*15。

只需要3次(log n = log 8 = 3)乘法,若采用自乘的方式,需要7次(n-1 = 8 - 1 = 7)乘法。

3. 代码如下

class Solution {
public:
    double myPow(double x, int n) {
        if (n == 0) return 1;
        if (n == 1) return x;
        if (n == -1) return 1/x;
        double a = myPow(x, n/2);
        if (n % 2 == 0) return a * a;
        else if (n < 0) return a * a * (1/x);
        else return a * a * x;
    }
};

你可能感兴趣的:(算法分析,Leetcode)