x的n次幂
题目
实现 pow(x,n)
注意事项
不用担心精度,当答案和标准输出差绝对值小于1e-3时都算正确样例
Pow(2.1, 3) = 9.261
Pow(0, 1) = 0
Pow(1, 0) = 1题解
用二分法优化累计相乘的过程。
public class Solution {
/**
* @param x the base number
* @param n the power number
* @return the result
*/
public double myPow(double x, int n) {
if (n < 0)
{
x = 1/x;
n = -n;
}
if (n == 0)
{
return 1;
}
else if (n == 1)
{
return x;
}
else if (n % 2 == 0)
{
return myPow(x, n/2) * myPow(x, n/2);
}
else
{
return x * myPow(x, n/2) * myPow(x, n/2);
}
}
}
Last Update 2016.11.17