- 问题来源
- 问题简介实现求幂函数 
解题思路
求一个数的n次幂,并不需要进行n次乘法,如
2的10次方,就是2的平方的5次方
2的平方的5次方,就是2的平方的平方的2次方再乘以2
以此类推
最后2的10次方只需进行4次乘法即可。
| 时间复杂度 | 空间复杂度 | 
|---|---|
| O(log(n)) | … | 
Code
#include <iostream>
using namespace std;
class Solution {
public:
    double myPow(double x, int n) {
        if (n == 0) {
            return 1;
        }
        if (x == 0 || x == 1) {
            return x;
        }
        if (n < 0) {
            x = 1 / x;
            n = -n;
        }
        double t = 1;
        while (n != 1) {
            if (n & 1) {
                t *= x;
            }
            x *= x;
            n /= 2;
        }
        return t * x;
    }
};
int main() {
    cout << Solution().myPow(2, 3) << endl;
    cout << Solution().myPow(2, -3) << endl;
    cout << Solution().myPow(2, 10) << endl;
    cout << Solution().myPow(2, 100) << endl;
    return 0;
}
