# Pow(x, n)

实现 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

提示:

以下错误的选项是?

## aop ### before ```c #include using namespace std; ``` ### after ```c int main() { Solution sol; double x = 2.00000; int n = 10; double res; res = sol.myPow(x, n); cout << fixed << setprecision(5) << res; return 0; } ``` ## 答案 ```c class Solution { public: double myPow(double x, int n) { if (n == 0) return 1.0; unsigned long long u = llabs(n); double ans = 1.0; while (u) { if (u & 1) ans *= x; x *= x; u >>= 1; } return n > 0 ? 1.0 / ans : ans; } }; ``` ## 选项 ### A ```c class Solution { public: double myPow(double x, int n) { if (n == INT_MIN) { double t = dfs(x, -(n / 2)); return 1 / t * 1 / t; } else { return n < 0 ? 1 / dfs(x, -n) : dfs(x, n); } } private: double dfs(double x, int n) { if (n == 0) { return 1; } else if (n == 1) { return x; } else { double t = dfs(x, n / 2); return (n % 2) ? (x * t * t) : (t * t); } } }; ``` ### B ```c class Solution { public: double myPow(double x, int n) { if (n == 0) return 1; if (n % 2 == 1) { double temp = myPow(x, n / 2); return temp * temp * x; } else if (n % 2 == -1) { double temp = myPow(x, n / 2); return temp * temp / x; } else { double temp = myPow(x, n / 2); return temp * temp; } } }; ``` ### C ```c class Solution { public: double helper(double x, int n) { if (n == 0) return 1.0; double y = helper(x, n / 2); return n % 2 == 0 ? y * y : y * y * x; } double myPow(double x, int n) { long long N = static_cast(n); if (N == 0) return 1; return N > 0 ? helper(x, N) : 1. / helper(x, -N); } }; ```