Pow(x, n)

Implement pow(x, n).

//目前写的不太好,坑比较多(n < 0),而且栈溢出和大数问题没考虑

//STL源码剖析上边参看源码

class Solution {
public:
    double pow(double x, int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (0 == n){
            return 1.0;
        }else if (1 == n){
            return x;
        }else if (-1 == n){
            return 1.0/x;
        }
        
        double ans = 1.0;
        if (n%2 == 1 || n%2 == -1) {
            ans *= n > 0? x : 1.0/x;
        }
        double a = pow(x,n/2);
        return ans*a*a;
    }
};

 

posted @ 2013-07-13 16:33  一只会思考的猪  阅读(146)  评论(0编辑  收藏  举报