[Leetcode] Pow (x, n)

Source: Internet
Author: User

[Leetcode] Pow (x, n)

Question:

Implement pow(x, n).

Analysis:
The question is very short, that is, to implement the power function of pow. Intuition tells me that the main requirement of this question is to reduce the time complexity of the program. If it is not clear, I submitted a while loop with the complexity of O (n) the error "Time Limit Exceed" is returned. The code is submitted for the first Time:

class Solution {public:    double myPow(double x, int n) {        double res = 1;        while(n > 0)        {            res*=x;            n--;        }        return res;    }};

Then the binary power is used to optimize the code and reduce the Time complexity to O (logn). The Code below is still a "Time Limit Exceed" error.

class Solution {public:    double myPow(double x, int n) {        if(n==0) return 1;        else        {            while((n&1)==0)            {                n>>=1;                x*=x;            }        }        double result=x;        n>>=1;        while(n!=0)        {            x*=x;        if((n&1)!=0)            result*=x;        n>>=1;        }        return result;    }};

It seems that the complexity must be reduced to O (1) to pass. I want to change my mind. Can I use something in the c ++ standard library and use the x ^ n = exp (log (x) * n) algorithm to reduce it to O (1 ), at the same time, if the value of the log function parameter is negative, it is successfully passed. The Code is as follows:

class Solution {public:    double myPow(double x, int n) {        if(x<0&&n%2==0)            x = -x;        if(x<0&&n%2!=0)          return -exp(log(-x)*n);        return exp(log(x)*n);    }};

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.