题目描述
实现函数double Power(double base, int exponent),求base的 exponent次方。
不得使用库函数,同时不需要考虑大数问题。
注意:
不会出现底数和指数同为0的情况
样例
样例1
输入:10 ,2
输出:100
样例2
输入:10 ,-2
输出:0.01
C++ 代码
class Solution1 {
public:
double Power(double base, int exponent) {
double res = 1;
int flag = 1;
if(exponent < 0) flag = -1, exponent = -exponent;
if(exponent == 0) return 1;
if(base == 0) return 0.0;
int i = exponent;
while(i--) res *= base;
if(flag == -1) res = 1/res;
return res;
}
};
class Solution{
public:
double Power(double base, int exponent) {
if(exponent == 0)
return 1;
if(exponent == 1)
return base;
int flag = 1;
if(exponent < 0) flag = -1, exponent = -exponent;
double result = Power(base, exponent >> 1);
result *= result;
if(exponent & 0x1 == 1)
result *= base;
if(flag == -1) result = 1/result;
return result;
}
};