您的位置:首页 > 其它

leetcode No50. Pow(x, n)

2016-07-28 16:27 369 查看

Question:

Implement pow(x, n).

Algorithm:

举个例子:假如是3的35次方,35=2^5+2^1+2^0,要注意超出INT_MAX的情况

Accepted Code:

class Solution {
public:
double myPow(double x, int n) {
if(n==0)return 1;
if(n==1)return x;
if(x==1)return x;
if(x==-1)
{
if(n%2==0)return -x;
else if(n%2==1)return x;
}
else if(n==INT_MAX&&x<1.0)return 0;
else if(n==INT_MIN&&x>1.0)return 0;
int flag=0;
if(n<0)
flag=1;
n=abs(n);
double res=1;
while(n>0)
{
int bit=1;
double tmp=x;
while(bit*bit<n)
{
tmp=tmp*tmp;
bit*=2;
}
n=n-bit;
res*=tmp;
if(res==0)
return 0;
}
if(flag==1)
{
res=(1/res);
return res;
}
else
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: