pow(x,n) leecode

https://oj.leetcode.com/problems/powx-n/ 提交地址 快速幂的使用,可以研究一下

 1 public class Solution {
 2     public double pow(double x, int n) {
 3         
 4         if(n==0) return 1.0;
 5         if(x==1) return 1.0;
 6         if(x==0)return 0;
 7         if(x==-1&&n%2==0) return 1; //有几个个数据一致通不过,才加入这么多判断,其实判断n=0 n>0 n<0,
 8         int f=1;
 9         if(n<0){ f=-1; n=-n;}
10         double res=1.0;
11         double temp=x;
12         
13         while(n!=0)
14         {
15             if((n&1)==1)
16             {
17               res*=temp;    
18             }
19             temp=temp*temp;
20             n=n>>1;
21         }
22             
23        if(f==1) return res;
24        else  return  1.0/res;
25        
26         
27         
28         
29         
30     }
31 }
原文地址:https://www.cnblogs.com/hansongjiang/p/3822646.html