劍指offer{面試題11 :數值的整數次方}
阿新 • • 發佈:2018-12-14
這道題的優解用到了一個數學公式 an=an/2an/2(n為偶數) an=an/2an/2*a(n為奇數) 還有一點問題就是邊界值的考慮,在本題中,我們要考慮分母不能為零,ex是負數,結果是倒數。 思路:遞迴
public class test11 { //一定要考慮邊界值問題, //所要考慮情況分為三類1.正常,2.分母為0,分母為負數 public double Power(double base,int ex) { int n = ex; if (ex==0) return 1; else if (ex<0) { if (base==0) throw new RuntimeException("分母不能為零"); n = -ex; } double res =PowerUsing(base,n); return ex<0? 1/res:res; } public double PowerUsing(double base,int n) { if (n==0) return 1; if (n==1) return base; double res = PowerUsing(base,n>>1); res*= res; if (n%2==1) res*=base; return res; } public static void main(String args[]) { test11 demo = new test11(); System.out.print(demo.Power(2,4)); } }