题目描述:
实现 pow(x, n) ,即计算 x
的整数 n
次幂函数(即,xn
)
解题思路:
乍一看就是一道简单的分治,x的n次方拆成x的n/2次方就可以了,但还是有些细节要注意。
class Solution {
public:
double myPow(double x, int n) {
if(n<0) return 1.0/help(x,-(long long)n);//需注意是否越界
return help(x,n);
}
double help(double x, long long n){
if(n==0) return 1;
if(n==1) return x;
double res = myPow(x, n/2);
if(n%2) return res*res*x;
return res*res;
}
};
写的期间报了一个错:
Line 19: Char 34: runtime error: negation of -2147483648 cannot be represented in type 'int'; cast to an unsigned type to negate this value to itself (solution.cpp) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:28:34
处理负指数时,若直接取-n,当n= -2147483648,-n就越界了,所以先把n转为long long,辅助函数的参数也用long long 就可以了。