admin管理员组

文章数量:1636900

Problem: Implement the library function implement Pow(x, n)


Solution:  该博客给出了几种不同的解题思路,值得参考。

                http://blog.csdn/fengbingyang/article/details/12236121


下面给出其中一种AC 6ms的代码实现

class Solution {
public:
    double myPow(double x, int n) {
        if (n == 0)
            return 1.0;
        else {

            if (n < 0)
            {
                //判断是否溢出
                if (n == INT_MIN)
                    return 1.0 / (pow(x, INT_MAX)*x);
                else
                    return 1.0 / pow(x, -n);
            }else{
                if (n % 2 == 0)
                {
                    double temp = myPow(x, n >> 1);
                    return temp * temp;
                }
                else{
                    double temp = myPow(x, (n - 1) >> 1);
                    return temp * temp * x;
                }

            }//else

        }//else
    }
};


本文标签: LeetCodepowimplement