leetcode-50-pow()
题目描述:
方法一:O(logn)递归:
class Solution:
def myPow(self, x: float, n: int) -> float:
if n == 0:
return 1
if n < 0:
return 1/self.myPow(x,-n)
if n&1:
return x*self.myPow(x,n-1)
return self.myPow(x*x,n//2)
迭代:
class Solution: def myPow(self, x: float, n: int) -> float: if n < 0: x,n = 1/x,-n ans = 1 while n > 0: if n&1: ans *= x x *= x n >>= 1 return ans
java版:
class Solution { public double myPow(double x, int n) { if(x==0) return 0; long b = n; double res = 1.0; if(b<0){ x = 1 / x; b = -b; } while(b>0){ if((b&1)==1) res *= x; x *= x; b >>= 1; } return res; } }