Q:给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。保证base和exponent不同时为0。
C:时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
T:
1.刚刚学习了快速幂,正好用上:https://www.cnblogs.com/xym4869/p/12240806.html
这个题要注意,exponent可能为负。
A:
double Power(double base, int exponent) {
double num = 1.0;
if(exponent<0){
base = 1/base;
exponent = -exponent;
}
while (exponent) {
if (exponent & 1) {
num = base * num;
}
base *= base;
exponent >>= 1;
}
return num;
}
2.直接内部函数调用:
double Power(double base, int exponent) {
return pow(base, exponent);
}
3.暴力法:
double Power(double base, int exponent) {
double num = 1.0;
if(exponent<0){
base = 1/base;
exponent = -exponent;
}
while(exponent--)
num = base * num;
return num;
}
4.递推法:
double Power(double base, int exponent) {
if(exponent == 0)
return 1;
if (exponent < 0) {
base = 1 / base;
exponent = -exponent;
}
return base * Power(base, exponent - 1);
}
原文地址:https://www.cnblogs.com/xym4869/p/12246315.html
时间: 2024-11-08 06:54:41