In order to limit its time complexity into nlog(n), binary search comes into my view.
- remember do not use **
- minus index is unavoidable here
- use recursion
class Solution:
"""
@param: x: the base number
@param: n: the power number
@return: the result
"""
def myPow(self, x, n):
# write your code here
if not x:
return 0
if n < 0:
pow = 1/self.myPow(x, -n)
return pow
if n == 0.0:
return 1.0
middle = n//2
pow = self.myPow(x, middle)
if n % 2:
pow = pow*pow*x
else:
pow = pow*pow
return pow
Bonus scene:
What's the lambda expression?
It is always used when we need a One-off function.
lambda x: x * x == function multiplication(x){ return x * x}
x is the variable
x * x is the function
Attention: Lambda is always followed by build-in function like filter or reduce or map(more)
网友评论