[Leetcode] Pow (x, n) x-th-square

Source: Internet
Author: User

Implement Pow (x, n).

This problem let us ask X of the N-square, if we simply use a for loop to X times their own n time, it would be too easy to think on the Leetcode, a word describing the pattern Tucson broken AH. OJ cannot pass because of timeout, so we need to optimize our algorithm so that it can work out the results more efficiently. We can use the recursive return binary calculation, each time the n is reduced by half, so that N will eventually shrink to 0, any number of 0 square is 1, this time we go back, if the n is even, directly the last recursive value to calculate a square return, if it is odd, you also need to multiply the value of the last X. Another thing that needs to be noticed is that N is likely to be negative, and for n is a negative number, we can first calculate a result with its absolute value and then take its reciprocal, the code is as follows:

Solution One

classSolution { Public:    DoublePowDoubleXintN) {if(N <0)return 1/Power (x,-N); returnPower (x, N); }    DoublePowerDoubleXintN) {if(n = =0)return 1; DoubleHalf = Power (x, N/2); if(n%2==0)returnHalf *half; returnX * Half *half; }};

There is also a way to use only one function, in each recursive check n positive and negative, and then do the corresponding transformation, the code is as follows:

Solution Two

classSolution { Public:    DoublePowDoubleXintN) {if(n = =0)return 1; DoubleHalf = POW (x, N/2); if(n%2==0)returnHalf *half; Else if(N >0)returnHalf * Half *x; Else returnHalf * Half/x; }};

[Leetcode] Pow (x, n) x-th-square

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.