leetCode 50题,实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,xn)。
Version 1.0
double myPow(double x, int n){
double y = 1;
for(int i = 0;i<n;i++){
y *=x;
}
return y;
}
问题:未考虑n为负数的场景,示例都没有看完。
Version 2.0
double myPow(double x, int n){
double y = 1;
if (n > 0 ) {
for(int i = 0;i<n;i++){
y *=x;
}
} else {
for(int i = 0;i< abs(n);i++) {
y /=x;
}
}
return y;
}
问题:超时,一个标为中等难度的确实不是暴力来搞就OK的。
Verison 3.0 看了题解,了解到快速幂算法。
double quickMul(double x, int n) {
if (n == 0) {
return 1.0;
}
double y = quickMul(x, n / 2);
return n % 2 == 0 ? y * y : y * y * x;
}
double myPow(double x, int n){
return n >= 0 ? quickMul(x,n): 1.0 / quickMul(x,-n);
}
问题:Line 10: Char 42: runtime error: negation of -2147483648 cannot be represented in type 'int'; cast to an unsigned type to negate this value to itself [solution.c]
做了一些尝试后还是没有想到原因,最后对比题解,发现需要定义一个long long来处理n。
Version 4.0
double quickMul(double x, long long n) {
if (n == 0) {
return 1.0;
}
double y = quickMul(x, n / 2);
return n % 2 == 0 ? y * y : y * y * x;
}
double myPow(double x, int n){
long long N = n;
return N >= 0 ? quickMul(x,N): 1.0 / quickMul(x,-N);
}
题目分析
1)快速幂算法的掌握和运用,pow(x,n)= pown(x,n/2)*pow(x,n/2)*(n%2==0?1:x)。
2) 有符号类型,负数取负存在溢出问题。