题目描述
- 实现函数
double Power(double base, int exponent)
,求 base 的 exponent 次方
- 不得使用库函数,同时不需要考虑大数问题
题目解读
代码
#include<iostream>
using namespace std;
class Solution {
public:
double Power(double base, int exponent) {
double result = 1.0;
for(int i = 0; i < exponent; i++){
result = result * base;
}
return result;
}
};
int main(){
Solution ss;
cout<<ss.Power(2, 3)<<endl;
}
class Solution {
public:
double Power(double base, int exponent) {
if(base == 0) return 0;
if(exponent == 0) return 1;
bool flag = true;
if(exponent < 0){
flag = false;
exponent = -1 * exponent;
}
double result = 1.0;
for(int i = 0; i < exponent; i++){
result = result * base;
}
if(flag == false){
result = 1.0 / result;
}
return result;
}
};
class Solution {
public:
double PowerCore(double base, int exponent){
double result = 0;
if(exponent == 1){
return base;
}
else{
result = PowerCore(base, exponent/2);
return result * result;
}
}
double Power(double base, int exponent) {
double result = 1.0;
bool flag = true;
if(base == 0) return 0;
if(exponent == 0) return 1;
if(exponent < 0){
flag = false;
exponent = -1 * exponent;
}
if(exponent/2 == 0){
result = PowerCore(base, exponent);
}
else{
result = PowerCore(base, exponent - 1);
result = result * base;
}
if(flag == false){
result = 1.0 / result;
}
return result;
}
};
- 和思路三思路一样,但是细节方面处理更加优越。判断偶数/奇数。除二运算
class Solution {
public:
double core(double base, int exponent){
if(exponent == 1){
return base;
}
else{
double tt = core(base, exponent>>1);
return tt * tt;
}
}
double Power(double base, int exponent) {
if(base == 0) return 0;
if(exponent == 0) return 1;
double result = 1.0;
bool flag = false;
if(exponent < 0){
flag = true;
exponent *= -1;
}
// 偶数
if(exponent&1 == 0){
result = core(base, exponent);
}
else{
result = base * core(base, exponent-1);
}
if(flag == true){
result = 1.0 / result;
}
return result;
}
};
总结展望
- 三种思路看书即可
- 很好的题目,想想自己只能想到第一种解法,真是需要多加练习