数值的整数次方(剑指offer面试题11)
实现函数 double Power(double base, int exponent),即乘方运算。
考虑问题
- exponet < 0 , 可以转化为 1.0 / Power(base, -1 *exponent)——负数与正数同时处理
- exponet < 0,并且base=0时,此时应该报错,因为此时0作为除数
- Power(0, 0) = 1
- Power(*, 0) = 1
思路一:常规思路
#include <iostream> using namespace std; bool InvalidInput = false; bool equal(double val1, double val2) { if((val1 - val2 < 0.0000001) && (val1 - val2 > -0.0000001)) return true; else return false; } double Power(double val, int exponent) { InvalidInput = false; if(equal(val, 0.0) && exponent < 0) { InvalidInput = true; return 0.0; } int absExponent = (unsigned int)(exponent); double rev = 1.0; if(exponent < 0) absExponent = (unsigned int)(-exponent); for(int i = 0; i < absExponent; ++i) rev *= val; if(exponent < 0) return 1.0 / rev; else return rev; } int main() { cout << Power(3.3, 3) << endl; cout << Power(3.3, -3) << endl; }
注意问题
- 计算机表示小数都有误差,所以直接用比较(==)会出现错误,解决的方法是两个数做差,与很小的数比较。
- 当base=0 && exponet < 0时,此时输入错误,用InvalidInput作为输出表示
思路二:递归
Pow (2, 4) = (Pow(2, 4), 2),这样做会节省时间
#include <iostream> using namespace std; bool InvalidInput = false; bool equal(double val1, double val2) { if((val1 - val2 < 0.0000001) && (val1 - val2 > -0.0000001)) return true; else return false; } double Power(double base, int exponent) { if(exponent == 0) return 1; else if(exponent == 1) return base; else if(exponent < 0) { if(equal(base, 0)) { InvalidInput = true; exponent = 0; return 0.0; } return 1.0 / Power(base, -1 * exponent); } else { double rev = Power(base, exponent >> 1); if(exponent & 1 == 0) { double rev = Power(base, exponent >> 1); return rev * rev; } else return Power(base, exponent - 1) * base; } } int main() { cout << Power(3.3, 3) << endl; cout << Power(3.3, -3) << endl; cout << Power(3.3, -3) << endl; cout << Power(2, -3) << endl; cout << "InvalidInput:" << InvalidInput << endl; cout << Power(0, -3) << endl; cout << "InvalidInput:" << InvalidInput << endl; }
结果
注意问题
- 判断奇数偶数,可以用val & 1,位操作比除法快
- 同理,处以2,可以用val / 2 代替