实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,xn)。不得使用库函数,同时不需要考虑大数问题。
示例 1:
输入:x = 2.00000, n = 10 输出:1024.00000
示例 2:
输入:x = 2.10000, n = 3 输出:9.26100
示例 3:
输入:x = 2.00000, n = -2 输出:0.25000 解释:2-2 = 1/22 = 1/4 = 0.25
提示:
-100.0 < x < 100.0
-231 <= n <= 231-1
-104 <= xn <= 104
1 class Solution { 2 public: 3 double myPow(double base, int exponent) { 4 double result = 1.0; 5 if (exponent == 0) { 6 return result; 7 } 8 if (exponent == -1) { 9 return 1.0 / base; 10 } 11 if (exponent & 1) { 12 return (base * myPow(base * base, exponent >> 1)); 13 } else { 14 return (myPow(base * base, exponent >> 1)); 15 } 16 } 17 };