【second】pow(x,n)

注意一点:n为负数时, n = -n; 有可能会溢出,当n == INT_MIN时

    double pow(double x, int n) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if(equal(x,0.0)&&n<=0)  //Invalid input
            return 0.0;
        unsigned int nn;
        bool bNega = false;
        if(n<0)
        {
            bNega = true;
            nn = -n;
        }else
            nn = n;
        
        double res =  helper(x,nn);
        if(bNega)
            res = 1.0/res;
        return res;
    }
    
    double helper(double x,unsigned int n)
    {
        if(n==0)
            return 1;
        if(n==1)
            return x;
        double res = helper(x,n>>1);
        if((n&0x1)==0)
            return res*res;
        else
            return res*res*x;
    }
    
    bool equal(double x,double y)
    {
        return (x-y<0.000001&&x-y>-0.000001);
    }

  

posted @ 2013-10-18 14:59  summer_zhou  阅读(171)  评论(0编辑  收藏  举报