【LeetCode】Pow(x, n)

Implement pow(x, n).

思路:快速幂运算,需要考虑指数为负数,同时底数为0的情况,这种属于异常数据,代码里没有体现。

class Solution {
public:

    double pow_abs(double x, unsigned int n)
    {
           if (n == 0)
	        {
	        	return 1;
	        }
	        if (n == 1)
	        {
	        	return x;
	        }
	    double res = pow(x, n>>1);
        res *= res;
	    if (n & 0x1 == 1)
	    {
		    res *= x;
	    }
	    return res;
    
    }
    double pow(double x, int n) {
        unsigned int abse = (unsigned int)(n);
        if(n < 0)
            abse = (unsigned int)(-n);
        double res = pow_abs(x, abse);
        if(n < 0)
            res = 1.0 / res;
        return res;
    }
};


你可能感兴趣的:(LeetCode)