/* * 50. Pow(x, n) * 2016-5-7 by Mingyang * Divide and Conquer 分成子问题------》recursive * Complexity is log(n), as he is dividing n by half all the way. * 我开始自己写的代码很烂,因为我并没有做到完全的divede成half,因为我不断地重复那个过程 * 后面改进的代码就克服了这个问题 */ public static double myPow1(double x, int n) { double res=0.0; if(n==0) return 1.0; boolean flag=false; if(n<0){ flag=true; n=-n; } if(n%2==0){ res=myPow(x,n/2)*myPow(x,n/2); }else{ res=myPow(x,n/2)*myPow(x,n/2)*x; } if(flag==true){ res=1.0/res; } return res; } public static double myPow(double x, int n) { if (n == 0) return 1.0; double half = myPow(x, n/2); if (n%2 == 0) { return half*half; } else if (n>0) { return half*half*x; } else { return half/x*half; } }
时间: 2024-10-11 03:50:14