LeetCode 50.Pow(x, n)

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/Oscar6280868/article/details/89022553

This question is relatively simple, is to achieve an exponential function, topics are as follows:
topic
First, how to answer this question, we might think, in many languages have built this function, you can directly call the library function, this time time complexity degree O ( 1 ) O (1) , there is a way violent solution, a write cycle, the number of cycles for the n n , every time multiplied x x , so the time complexity of this time O ( N ) O (N) , which are relatively easy way to think of.
Next we can be analyzed from another perspective, we can use a recursive method, the entire n n -th power divided by two, of course, necessary to determine n n parity until n n is 1, the code is as follows:

class Solution(object):
    def myPow(self, x, n):
        """
        :type x: float
        :type n: int
        :rtype: float
        """
        if not n:
            return 1
        if n < 0:
            return 1/self.myPow(x, -n)
        if n % 2:
            return x * self.myPow(x, n-1)
        return self.myPow(x * x, n / 2)

This recursive method, it can be exponential function recursively split, hoping to help everyone understand the recursive algorithm, thank you.

Guess you like

Origin blog.csdn.net/Oscar6280868/article/details/89022553