您的位置:首页 > 理论基础 > 数据结构算法

微软等数据结构+算法面试100题(26)--数值的整数次方

2012-11-11 16:04 423 查看
/*
71.数值的整数次方。
题目:实现函数double Power(double base, int exponent),求base 的exponent 次方。
*/

/*
例如要计算2^5;n是次方数,res是返回值。tmp中间变量
n       res      tmp
6         1         2
3         1         2^2
1       2^2      2^4
0       2^6
整个计算过程就是n次方每次都向右移一位。说明现在是tmp^n。如果n是奇数的话。那么肯定要使res*=tmp;这样就变成了
tmp^n-1。而n-1是偶数。
*/

double Power(double base, int exponent)
{
double res=1,tmp=base;
while(exponent)
{
if((exponent&1)==1)
res*=tmp;
tmp=tmp*tmp;
exponent=exponent>>1;
}
return res;
}

void PowerTest()
{
while(1)
{
double base=0.0;
cout<<"base : ";
cin>>base;
int exponent=0;
cout<<"exponent : ";
cin>>exponent;
cout<<"base^exponent : "<<Power(base,exponent)<<endl;
cout<<"base^exponent : "<<std::pow(base,exponent)<<endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐