Leetcode 50 POW (x, y)

Source: Internet
Author: User

Implement POW (X,N), Which calculatesXRaised to the powerN(Xn ).

Example 1:

Input: 2.00000, 10Output: 1024.00000

Example 2:

Input: 2.10000, 3Output: 9.26100

Example 3:

Input: 2.00000, -2Output: 0.25000Explanation: 2-2 = 1/22 = 1/4 = 0.25

Note:

  • -100.0 <X<100.0
  • NIs a 32-bit signed integer, within the range [? 231,231? 1]

Maybe I think too much, because the negative number range of the int is more than the positive number range. to convert it to a positive integer, we need to consider another range.

class Solution {public:    double myPow(double x, int n) {        long long m=n;        if(n<0){return pow(1/x, 0-m);}        return pow(x, n);    }    double pow(double x, long long n) {        if(0==n){return 1.0;}        double a=0.0;        a = pow(x, n/2);        // cout<<a<<"   "<<n<<endl;        if(n%2){            return a*a*x;        }else{            return a*a;        }    }};

I still feel bad. I found an article well written.

80021207

Leetcode 50 POW (x, y)

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.