LeetCode: Pow(x, n)

Problem:

Implement pow(x, n).

Subscribe to see which companies asked this question

 
 考虑到指数为负的情况 利用二分来求结果 时间复杂度O(logn) 
 1 class Solution {
 2 public:
 3     double myPow(double x, int n) {
 4         if(n<0) 
 5             return 1.0/mypow(x,-n);
 6         return mypow(x,n);
 7     }
 8     
 9     double mypow(double base,unsigned int expo)
10     {
11         if(expo==0) return 1;
12         
13         double result=mypow(base,expo >> 1);
14             result*=result;
15         if(expo & 0x1 == 1)
16             result*=base;
17         return result;
18     }
19 };

 

posted @ 2016-02-29 17:25  尾巴草  阅读(128)  评论(0编辑  收藏  举报