050 Pow(x, n)
实现 pow(x, n)。
示例 1:
输入: 2.00000, 10
输出: 1024.00000
示例 2:
输入: 2.10000, 3
输出: 9.26100
详见:https://leetcode.com/problems/powx-n/description/
Java实现:
方法一:
class Solution { public double myPow(double x, int n) { if(n<0){ return 1/helper(x,-n); } return helper(x,n); } private double helper(double x,int n){ if(n==0){ return 1; } double half=helper(x,n/2); if(n%2==0){ return half*half; } return x*half*half; } }
方法二:
class Solution { public double myPow(double x, int n) { double res=1.0; for(int i=n;i!=0;i/=2){ if(i%2!=0){ res*=x; } x*=x; } return n<0?1/res:res; } }
参考:https://www.cnblogs.com/grandyang/p/4383775.html