给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
保证base和exponent不同时为0
考虑快速幂
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| class Solution { public: double Power(double base, int exponent) { bool need_reverse = false; if (exponent < 0) { exponent = - exponent; need_reverse = true; } if (exponent == 0) { return 1; } else if (exponent == 1) { if (need_reverse) { return 1 / base; } else { return base; } } else { double res = 1; while (exponent) { if (exponent & 1) { res *= base; } base *= base; exponent >>= 1; } if (need_reverse) { return 1 / res; } else { return res; } } } };
|