We can use quick power to slove this problem


  • 0
    D

    We can use quick power to slove this problem

    This is my source code that used quick power

    class Solution {
    public:
        
        //quick power
        double pow(double x, int n)
        {
            if(n == 0) return 1;
            if(n == 1) return x;
            
            double result = pow(x, n / 2);
            result *= result;
            if(n & 1) result *= x;
            
            return result;
        }
        
        double myPow(double x, int n) {
            
            x = pow(x, n < 0 ? -1 * n : n);  //get the number pow(x, |n|)
            
            if(n < 0) x = 1 / x;   //if n i a negative number
            
            return x;  //return result
        }
    };
    

    But I find that we can direct call the pow function in C++

    for example

    class Solution {
    public:
        double myPow(double x, int n) {
            return pow(x,n);
        }
    };
    

Log in to reply
 

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