您的位置:首页 > 其它

[Leetcode]Pow(x, n)

2015-10-26 20:31 351 查看
Implement pow(x, n).

Have you met this question in a real interview?

class Solution {
public:
/*algorithm: divde and conqure
*/
double myPow(double x, int n) {
if(n == 0)return 1.0;
double half = myPow(x,n/2);
double ret = half*half;
if(n%2){
if(n > 0)ret *= x;
else ret /= x;
}
return ret;
}
};
class Solution {
public:
/*algorithm: divde and conqure
*/
double powSub(double x,long n){//long ,instead of int ,otherwise overflow
if(n == 0)return 1.0;
double half = powSub(x,n/2);
double ret = half*half;
if(n%2)ret *= x;
return ret;
}
double myPow(double x, int n) {
if(n < 0)return 1/powSub(x,-n);
return powSub(x,n);
}
};


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法