50. Pow(x, n)
Implement pow(x, n).
My Solution
class Solution(object):
myPow = pow
Reference (转)
1
class Solution:
def myPow(self, x, n):
return x ** n
2
class Solution:
def myPow(self, x, n):
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)
3
class Solution:
def myPow(self, x, n):
if n < 0:
x = 1 / x
n = -n
pow = 1
while n:
if n & 1:
pow *= x
x *= x
n >>= 1
return pow