Pow(x, n)

public class Solution {
    public double pow(double x, int n) {
        // Start typing your Java solution below
        // DO NOT write main() function
       
       if(x<0.0001&&n==0)return 1;
       if(n==0)return 1;
       int temp = Math.abs(n);
       double ans = pow_pos(x,temp);
       if(n>=0)return ans;
       //else return 1/ans;
       return 1/ans;
    }
    private double pow_pos(double x,int n){
        if(n==1)return x;
        if(n%2==0){
            double temp = pow_pos(x,n/2);
            return temp*temp;
        }
        else {
            double temp = pow_pos(x,n/2);
            return temp*temp*x;
        }
    }
}

發佈了83 篇原創文章 · 獲贊 1 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章