码迷,mamicode.com
首页 > 其他好文 > 详细

Pow(x, n)

时间:2014-11-21 10:36:20      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   os   sp   on   div   log   

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)

标签:style   blog   io   color   os   sp   on   div   log   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!