1,题目要求
Implement pow(x, n), which calculates x raised to the power n (xn).
Example 1:
Input: 2.00000, 10
Output: 1024.00000
Example 2:
Input: 2.10000, 3
Output: 9.26100
Example 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 [−231, 231 − 1]
实现pow(x,n),它计算x增加到幂n(xn)。
2,题目思路
对于这道题,要求实现一个幂乘的函数。
其中,题目中给出的例子可以看出,首先,返回值是一个double类型。其次,幂次指数有可能是负值,因此,针对这些特点,需要有特别的处理。
我们在进行幂次乘积的过程中可以发现:
- 一个幂次n,如果是偶数,那么可以将幂次分解为(x*x)n/2的形式。
- 如果是奇数,也可以分解为:x*(x*x)n/2的形式。
依照上述的特点,我们在实现算法是进行简化,减少计算的需求。
3,代码实现
static auto speedup = [](){
ios::sync_with_stdio(false);
cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
double myPow(double x, int n) {
long nn = n;
if(nn == 0)
return 1;
if(nn < 0){
nn = -nn;
x = 1.0/x;
}
return (nn%2 == 0) ? myPow(x*x, nn/2) : x*myPow(x*x, nn/2);
}
};