50. Pow(x, n)

Implement [pow(*x*, *n*)](http://www.cplusplus.com/reference/valarray/pow/), which calculates *x* raised to the power *n* (xn).

**Example 1:**

1
2
Input: 2.00000, 10
Output: 1024.00000
**Example 2:**
1
2
Input: 2.10000, 3
Output: 9.26100
**Example 3:**
1
2
3
Input: 2.00000, -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
**Note:** - -100.0 < *x* < 100.0 - *n* is a 32-bit signed integer, within the range [−2^31, 2^31 − 1] 思路:原以为是如何处理大数问题,因为感觉n的值为有符号的整数,会是一个大数。看别人写的代码,采用double来存储x的数值。double的范围在+/- 1.7e +/-308,如果而n和x分别采用最大值,即x=100, n=2.1*10^9, 则pow(x, n) = 10e10^9,应该是远超double的范围了。但是代码是能通过OJ的,不知道为什么。
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
double myPow(double x, int n) {
if (n < 0) return 1 / power(x, -n);
return power(x, n);
}
double power(double x, int n) {
if (n == 0) return 1;
double half = power(x, n / 2);
if (n % 2 == 0) return half * half;
return x * half * half;
}
};
结果:4ms, 98.54%