首页 > 其他 > 详细

Pow(x, n)

时间:2014-11-21 10:35:17      阅读:273      评论:0      收藏:0      [点我收藏+]

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;
}

 

Pow(x, n)

原文:http://www.cnblogs.com/wuchanming/p/4112046.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!