剑指offer16:数字的整数次方
题目:给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。保证base和exponent不同时为0
解:非0数的0次幂为1,0的非0次幂为0. 需要区分bases的正负.
class Solution {
public:
double Power(double base, int exponent) {
if(exponent==0)
return 1;
if(base==0)
return 0;
double result = 1.0;
if(exponent >0){
while(exponent){
result = result * base;
exponent--;
}
return result;
}
else{
exponent=abs(exponent);
while(exponent){
result = result * base;
exponent--;
}
return 1.0 / result;
}
}
};