LeetCode 50. Pow(x, n)

1. 题目描述

Implement pow(x, n).

2. 解题思路

主要就是需要考虑几类情况, 底数为 -1, 1, 指数为 0, 正数, 负数;
而对于正常的指数为正的情况:
我们可以考虑使用这样的数学技巧

res(x,n)={res(x2,n/2)xres(x2,n/2)ifn%2==1else

3. code

class Solution {
public:
    double myPow(double x, int n) {
        if (n == 0)
            return 1.0;

        if (fabs(x - 1) < 1e-6)
            return 1.0;

        if (fabs(x + 1) < 1e-6)
            return n % 2 ? -1.0 : 1.0;

        if (n < 0){
            long long tmp = n;
            tmp = -tmp;
            return _myPow(1 / x, tmp);
        }

        return _myPow(x, n);
    }

    double _myPow(double x, long long n) {
        if (n == 1)
            return x;

        if (n % 2){
            return x * _myPow(x * x, n >> 1);
        }
        return _myPow(x * x, n >> 1);
    }
};

4. 大神解法

4.1 demo1

他这里特殊处理了指数为0, 正数, 负数的情况

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

4.2 demo2

After reading some good sharing solutions, I'd like to show them together. You can see different ideas in the code.

1. nest myPow

double myPow(double x, int n) {
    if(n<0) return 1/x * myPow(1/x, -(n+1));
    if(n==0) return 1;
    if(n==2) return x*x;
    if(n%2==0) return myPow( myPow(x, n/2), 2);
    else return x*myPow( myPow(x, n/2), 2);
}
2. double myPow

double myPow(double x, int n) { 
    if(n==0) return 1;
    double t = myPow(x,n/2);
    if(n%2) return n<0 ? 1/x*t*t : x*t*t;
    else return t*t;
}
3. double x

double myPow(double x, int n) { 
    if(n==0) return 1;
    if(n<0){
        n = -n;
        x = 1/x;
    }
    return n%2==0 ? myPow(x*x, n/2) : x*myPow(x*x, n/2);
}
4. iterative one

double myPow(double x, int n) { 
    if(n==0) return 1;
    if(n<0) {
        n = -n;
        x = 1/x;
    }
    double ans = 1;
    while(n>0){
        if(n&1) ans *= x;
        x *= x;
        n >>= 1;
    }
    return ans;
}
5. bit operation

class Solution {
public:
    double pow(double x, int n) {
        if(n<0){
            x = 1.0/x;
            n = -n;
        }
        int unsigned m = n;
        double tbl[32] = {0};
        double result = 1;
        tbl[0] = x;
        for(int i=1;i<32;i++){
            tbl[i] = tbl[i-1]*tbl[i-1];
        }
        for(int i=0;i<32;i++){
            if( m & (0x1<<i) )
            result *= tbl[i];
        }
        return result;
    }
};

If you have other ideas, please leave it below. Thanks.

你可能感兴趣的:(LeetCode)