/* * 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 myPow(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; } //上面是我写的代码,不对,因为当n为负无穷的时候,n=-n的值会overflow,abs(MININT) > MAXINT //其实根本不需要来进行符号的变换,直接做,把x放分母就行了 public double myPow1(double x, int n) { if(n==0) return 1; if(n==1) return x; double y=myPow1(x,n/2); if(n%2!=0) { if(n>0) return y*y*x; else return y*y/x; } return y*y; }