题目:
50. Pow(x, n)
Implement pow(x, n).
题目描述:实现x的n次方
一开始用蛮力法计算,提交代码以后系统判断计算超时,所以采用分治的思想,先计算x的n/2次方,再将结果求平方即可,调试过程中主要问题就是精度问题,当x为分数、且n较大时,结果可能为0,在求解问题中可能出现0做分分母的情况,如果改为乘法 则可以解决这个问题(以下代码并未修改)
贴代码:
double myPow(double x, int n) {
int index = n;
double result = 1;
double sqr;
if (x == 0)
return x;
if (n == 1)
return x;
if (n == 0)
return 1;
if(n < 0)
index = -n;
if (index % 2 == 0) {
// index is even
sqr = myPow(x, index / 2);
result = sqr * sqr;
}
else {
// index is odd
sqr = myPow(x, (index + 1) / 2);
if (x == 0)
return 1;
result = sqr * sqr / x;
}
if (result == 0)
return 0;
if (n < 0) {
result = 1 / result;
}
return result;
}leetcode时间排名:
本文介绍了一种高效计算x的n次方的方法,针对LeetCode上的50.Pow(x, n)问题,通过分治思想减少计算次数,避免了直接计算带来的超时问题。文章详细解析了算法的具体实现过程,并讨论了在不同情况下如何处理精度问题。
534

被折叠的 条评论
为什么被折叠?



