Leetcode: Pow (x, n)

Source: Internet
Author: User

Leetcode: Pow (x, n)

I. Question

The question is very clear, that is, to implement the pow () function.

Ii. Analysis

After seeing the question, I first thought of computing one by one, and thought that it would time out. This reduces the number of operations. There is no difficult idea.

Although the idea is binary, there are different implementations. The following three types are used:

While implementation:

class Solution {public:    double pow(double x, int n) {        if(n == 0)        return 1.0;        if(n == 1)        return x;        int nflag = abs(n);        int nflag2 = nflag;        double xflag = abs(x);        double xflag2 = xflag;        int s = 1;        while(nflag / 2 > 0){        xflag2 = xflag2 * xflag2;        nflag = nflag / 2;        s = s * 2;        }        xflag2 = xflag2 * pow(xflag, nflag2 - s);        if(x < 0 && n % 2 == 1)        xflag2 = -xflag2;        if(n < 0)        xflag2 = 1 / xflag2;        return xflag2;    }};

Recursive Implementation 1:

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

Recursive Implementation 2:

class Solution {public:    double pow(double x, int n) {    if(n == 0)    return 1.0;    double res = pow(x,n/2);    if(n % 2 != 0){    if(n > 0)    return (res * res * x);    else    return (res / x * res);    }    return (res * res);    }};

Related Article

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.