- /*
- 题目:
- 实现函数 double Power(double base,int exponent),
- 求 base 的 exponent 次方.
- */
- /*
- 思路:
- 本题需要考虑的情况较多:
- 1,0 的负数次方报错.
- 2, 判断 double 值为 0, 需要使用精度.
- 3, 考虑 exponent 为负数的情况.
- 可创新的点:
- 求 x(n 次方), 可用 x(n/2 次方)*2(n/2 次方) x 为偶数
- 求 x(n 次方), 可用 x(n/2 次方)*2(n/2 次方)*x x 为奇数
- */
- #include<iostream>
- #include<string.h>
- #include<algorithm>
- #include<cmath>
- using namespace std;
- #define MIN_VALUE 1e-8
- bool g_InvalidInput = false;
- bool equal0(double num1){
- if(abs(num1) <MIN_VALUE) return true;
- return false;
- }
- double PowerWithUnsignedExponent(double base,unsigned int exponent){
- if(exponent == 0){
- return 1;
- }
- if(exponent == 1){
- return base;
- }
- // 用位运算代替除法
- double result = PowerWithUnsignedExponent(base,exponent>>1 );
- result *= result;
- // 判断 exponent 为奇数时, 需要多乘一次.
- // 用位运算代替取模
- if(exponent &0x1 == 1){
- result *= base;
- }
- return result;
- }
- double Power(double base,int exponent){
- if(equal0(base) && exponent < 0){
- g_InvalidInput = true;
- return 0.0;
- }
- 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,9)<<endl;
- }
来源: http://www.bubuko.com/infodetail-3287973.html