This question is relatively simple, is to achieve an exponential function, topics are as follows:
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
, there is a way violent solution, a write cycle, the number of cycles for the
, every time multiplied
, so the time complexity of this time
, which are relatively easy way to think of.
Next we can be analyzed from another perspective, we can use a recursive method, the entire
-th power divided by two, of course, necessary to determine
parity until
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.