guodongxiaren / OJ

4 stars 3 forks source link

LeetCode 50: #41

Open guodongxiaren opened 4 years ago

guodongxiaren commented 4 years ago

实现 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] 。

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/powx-n 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

guodongxiaren commented 4 years ago

分治法。说是二分不恰当。

用分治法解,就是所谓的『快速幂』。不这样做会超时。

class Solution {
public:
    double myPow(double x, int n) {
        long int N = n;
        if (N < 0) {
            x = 1/x;
            N *= -1;
        }
        if (N == 0) {
            return 1.0;
        } else if (N == 1) {
            return x;
        }
        double result = x;

        long int temp=1;
        while (temp < N){
            result *= result;
            temp *= 2;//记录已经指数运算的部分
        }
        return result * myPow(x, N-temp);//n-temp表示剩余未处理的指数
    }
};
guodongxiaren commented 4 years ago

注意n是-2147483648的时候,转整数会超过int范围。要用int改存。

另外就是如果n是负数。把x换成1/x。n再改成正数,后面就顺当了。