Implement pow(x, n), which calculates x raised to the power n (xn).
阿新 • • 發佈:2018-12-20
Implement pow(x, n), which calculates x raised to the power n (xn).
thoughts:
求一個數的power 數目,
虛擬碼如下:
如果n=0 ,返回1.否則返回1,返回的2,
n=-1,返回-1,返回1/x;
其他程式碼如下:
public class Power { public double myPow(double x,int n){ if(n==0){ return 1; }else if (n==1){ return x; }else if(n==-1){ return 1/x; } if(n%2==0){ double half=myPow(x,n/2); return half*half; } else{ double half=myPow(x,(n-1)/2); return half* half* x; } } }