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);
}
};