实现函数 doubule Power(double base, int exponent),求base的exponent次方,不得使用库函数,同时不需要考虑大数问题。
解法一:直接写出函数,而未考虑base为0,且exponent为负的情况。
double MyPower1(double dBase, int iExporent) { double dRes = 1.0; for (int i=1; i<=iExporent; i++) { dRes *= dBase; } return dRes; }当base为0,且exponent为负数时,就会出现对0求倒数的情况,导致程序崩溃。
解法二:较完整的解法,未考虑base为0,且exponent为负的情况。程序中添加了g_InvalidInput用来表示错误类型。添加了equal()函数,用于确定double类型的数值是否相等,并肩iExporent转换成了无符号整数。
bool g_InvalidInput = false; double MyPower2(double dBase, int iExporent) { g_InvalidInput = false; if (equal(dBase,0) && iExporent<0){ g_InvalidInput = true; return 0.0; } unsigned int absExporent = (unsigned int )iExporent; if (iExporent < 0){ absExporent = (unsigned int )(-iExporent); } double dRes = PowerWithUnsignedExpoent(dBase , absExporent); if (iExporent < 0){ dRes = 1.0/dRes; } return dRes; } double PowerWithUnsignedExpoent(double dBase, unsigned int iExporent) { double dRes = 1.0; for (unsigned int i=1; i<=iExporent; i++) { dRes *= dBase; } return dRes; } bool equal(double dA, double dB) { double dSub = dA-dB; if (dSub < 0.0000001 && dSub > -0.0000001){ return true; }else{ return false; } }解法三:效率较高的解法。在方法二的基础上考虑如下公式
通过上述公式,可以将计算指数的次数减少到O(logN)次,同时可以使用递归。下面代码中的另外两处优化的地方是,将除以2使用右移替代;将取模运算,用和0x1进行与运算,提高了程序的运行效率。
double MyPower3(double dBase, int iExporent) { g_InvalidInput = false; if (equal(dBase,0) && iExporent<0){ g_InvalidInput = true; return 0.0; } unsigned int absExporent = (unsigned int )iExporent; if (iExporent < 0){ absExporent = (unsigned int )(-iExporent); } double dRes = PowerWithUnsignedExpoent_Recursive(dBase , absExporent); if (iExporent < 0){ dRes = 1.0/dRes; } return dRes; } double PowerWithUnsignedExpoent_Recursive(double dBase, unsigned int iExporent) { if (iExporent == 0) return 1; if (iExporent == 1) return dBase; double dRes = PowerWithUnsignedExpoent_Recursive(dBase, iExporent >> 1); dRes *= dRes; if (iExporent & 0x1 == 1){ dRes *= dBase; } return dRes; }