Leetcode 50. Pow(x, n) x的n次方 in Java

50. Pow(x, n)

 
  • Total Accepted: 106878
  • Total Submissions: 388728
  • Difficulty: Medium

 

Implement pow(xn).

 

public class Solution {
    public double myPow(double x, int n) {
        int sign=1;
        if(n<0){
            sign=-1;
            n=-n;
        }
        return sign<0? 1/pow(x,n) : pow(x,n) ;
    }
        
        
    public double pow(double x,int n){
        if(n==0) return 1;
        if(n==1) return x;
        if(n%2==0) {
            double tmp=pow(x,n/2);
            return tmp*tmp;
        }else{
            double tmp=pow(x,n/2);
            return tmp*tmp*x;
        }
    }
    
}

 

posted on 2016-09-08 21:23  颜YQ  阅读(787)  评论(0编辑  收藏  举报

导航