O(1) solution is possible


  • 0
    C

    Interesting no one has mentioned this method. I turned out implementing Taylor series of exp and log.

    Not sure this is a pride or a shame. More likely a shame....


  • -4
    H

    class Solution {
    public:
    double pow(double x, int n)
    {
    double result;
    if(x==1.00000)
    return x;
    else if(x==-1.00000)
    {
    if(n%2==0)
    return -x;
    else
    {
    return x;
    }
    }
    if(n>0)
    {
    result=Get_Result(x,n);
    return result;
    }
    else if(n<0)
    {
    n=0-n;;
    result=1.0/Get_Result(x,n);
    return result;
    }
    else
    return 1.0;
    }
    double Get_Result(double x,int n)
    {
    if(n==1)
    return x;
    else if(n==0)
    return 1.0;
    else
    {
    if(n%2==0)
    {
    double tt=Get_Result(x,n/2);
    return tttt;
    }
    else
    {
    double tt=Get_Result(x,(n-1)/2);
    return tt
    tt*x;
    }
    }
    }
    };


  • 2
    Y

    Maybe you want to use this

    e^x = 1+x+x^2/2!+x^3/3!+……+x^n/n!+…… 
    

    to solve the question?
    But I'm quite puzzled...

    How to get the value of n ?

    And... How to calculate pow(e,x)?


  • 0
    T

    Can you please elaborate more?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.