题目描述
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
保证base和exponent不同时为0
一般解法:
直接相乘;
1 class Solution01 { 2 public: 3 double Power(double base, int exponent) { 4 if (exponent == 0 || equal(base, 0.0, 0.0))return 1; 5 double res = 1.0; 6 for (int i = 1; i <= abs(exponent); ++i) 7 res *= base; 8 return exponent < 0 ? (1.0 / res) : res; 9 } 10 };
高效率解法:
使用递归:
1 class Solution02 { 2 public: 3 double Power(double base, int exponent) { 4 if (exponent == 0 || equal(base, 0.0, 0.0))return 1; 5 double res = PowerMul(base, abs(exponent)); 6 return exponent < 0 ? (1.0 / res) : res; 7 } 8 double PowerMul(double base, unsigned int exponent) 9 { 10 if (exponent == 0)return 1; 11 if (exponent == 1)return base; 12 13 double res = PowerMul(base, exponent >> 1); 14 res *= res; 15 if (exponent & 1)//奇数 16 res *= base; 17 return res; 18 } 19 };