50 Pow(x, n)(求x的n次方Medium)

题目意思:x为double,n为int,求x的n次方

思路分析:直接求,注意临界条件

 1 class Solution {
 2 public:
 3     double myPow(double x, int n) {
 4         if(x==1.0)return x;
 5         else if(x==-1.0){
 6             if(n%2==0)return 1.0;
 7             else return -1.0;
 8         }
 9         double ans=1.0;
10         int flag=abs(n);
11         while(flag--&&abs(ans)>0.0000001)ans*=x;
12         if(n>0)return ans;
13         else return 1.0/ans;
14     }
15 };

时间复杂度:O(n)

运行时间:20ms

此题并没有用什么算法,有时间再研究

posted @ 2015-06-13 01:51  影翕  阅读(147)  评论(0编辑  收藏  举报