Pow(x, n)

Implement pow(xn).

 

C++实现代码:

#include<iostream>
using namespace std;

class Solution
{
public:
    double pow(double x, int n)
    {
        if(x==0&&n==0)
            return 1;
        if(x==0)
            return 0;
        if(n==0)
            return 1;
        if(n==1)
            return x;
        if(n<0)
        {
            n=-n;
            x=1/x;
        }
        if(n%2)
            return x*pow(x*x,n/2);
        else
            return pow(x*x,n/2);
    }
};

int main()
{
    Solution s;
    cout<<s.pow(2,2)<<endl;
}

另一种,不知道为什么通不过:

#include<iostream>
using namespace std;

class Solution
{
public:
    double pow(double x, int n)
    {
        if(x==0&&n==0)
            return 1;
        if(x==0)
            return 0;
        if(n==0)
            return 1;
        if(n==1)
            return x;
        if(n<0)
        {
            n=-n;
            x=1/x;
        }
        if(n%2)
            return x*pow(x,n/2)*pow(x,n/2);
        else
            return pow(x,n/2)*pow(x,n/2);
    }
};

int main()
{
    Solution s;
    cout<<s.pow(2,2)<<endl;
}

 

posted @ 2014-11-21 09:16  Jessica程序猿  阅读(182)  评论(0编辑  收藏  举报