题目:
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
思路:
看题目似乎很简单,循环相乘不就行了吗?不是的。
需要考虑几个问题:
1、exponent为0或者负数;
2、base为0且exponent为负数,其中判断base是否为0,需要考虑base为double类型;
3、高效的计算方法:分治;
代码:
#include <iostream> #include <stdlib.h> using namespace std; bool equal(double num1,double num2){ if(abs(num1-num2)<0.0000001) return true; else return false; } double PowerWithUnsignedExponent(double base,unsigned int absExponent){ if(absExponent==0) return 1; if(absExponent==1) return base; double result=PowerWithUnsignedExponent(base,absExponent>>1); result=result*result; if((absExponent&0x1)==1) result=result*base; return result; } double Power(double base,int exponent){ unsigned int absExponent=(unsigned int)exponent; if(exponent<0) absExponent=(unsigned int)(-exponent); double result=PowerWithUnsignedExponent(base,absExponent); if(exponent<0) result=1.0/result; return result; } int main() { cout<<Power(2,-3)<<endl; cout<<Power(0,-1)<<endl; cout<<Power(5,0)<<endl; return 0; }
在线测试OJ:
http://www.nowcoder.com/books/coding-interviews/1a834e5e3e1a4b7ba251417554e07c00?rp=1
AC代码:
class Solution { public: double Power(double base, int exp) { int exponent=exp>0?exp:(-exp); double p,result; if(exponent==0) return 1; if(exponent==1) return base; p=Power(base,exponent>>1); result=p*p; if(exponent&0x1) result=p*p*base; if(abs(result-0.0)<0.00000001) return result; return exp>0?result:(1/result); } };