[Leetcode Long March series] Pow (x, n)

Source: Internet
Author: User

Original question:

Implement POW (X,N).

Idea: recursive Calculation of pow.

class Solution {public:    double pow(double x, int n) {       long long int mid = n/2;       int d = n%2;       if(n==0) return 1;       if(n==1) return x;       if(d==1) return pow(x, (n/2)+1) * pow(x, n/2);       else return pow(x, n/2) * pow(x, n/2);    }};

Timeout at the boundary value.

INT-2147483648 ~ + 2147483647 (4 bytes)

class Solution {public:    double pow(double x, int n) {       long long num = n;       if(num==0) return 1.0;       if(num==1) return x;       if(num<0) return 1.0/pow(x, -num);       double half = pow(x,num>>1);       if(num%2==0) return half*half;       else return half*half*x;    }};
If n is a negative value, the overflow occurs after negative values are obtained. Re


class Solution {public:    double pow(double x, int n) {       if(n==0) return 1.0;       if(n==1) return x;       if(n<0 && n!=INT_MIN) return 1.0/pow(x, -n);       if(n==INT_MIN) return 1.0/(pow(x, INT_MAX)*x);       double half = pow(x,n>>1);       if(n%2==0) return half*half;       else return half*half*x;    }};
Consider the minimum int_min, that is, the-2147483648 take negative will overflow, so special processing is required.

AC

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.