Leetcode---50. Pow (x, N)

Source: Internet
Author: User

Title Link: Pow (x, N)

Implement POW (x, N).

The requirement for this problem is to implement the POW (x, n) function.

The n power of X is obtained. Direct violent thinking, multiply x by itself n times, time complexity O (n). When n is very large, the calculation time is too long.

Consider converting n to a binary number, i.e. n = a0*2^0 + a1*2^1 + a2*2^2 + ... + an*2^n. The n power of x is X^n = x^ (a0*2^0 + a1*2^1 + a2*2^2 + ... + an*2^n) = x^ (a0*2^0) * x^ (a1*2^1) * x^ (a2*2^2) * ... * x^ (an*2^n).

For example, when n equals 11,

n=11:   1    0   1    1 (高位->低位)结果:  x^4      x^2  x^1(连乘的结果)

So, divide n by 2 each time, multiply x by x, so that when a bit of binary is 1 o'clock, the x in this case is multiplied by the result.

Note that when n is negative, you need to divide the result by 1. At the same time, because a negative number is shifted right by 1, it is not divided by 2, so instead of dividing by 2, the shift is not used to increase speed.

Complexity of Time: O (LOGN)

Space complexity: O (1)

1 class Solution2 {3  Public:4     Double POW(Double x, int N)5     {6         Double Res = 1.0;7          for(int I = N; I != 0; I /= 2, x *= x)8             if(I & 1)9                 Res *= x;Ten         return N >= 0 ? Res : 1.0 / Res; One     } A };

Reprint please indicate source: Leetcode---50. Pow (x, N)

Leetcode---50. Pow (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.