您的位置:首页 > 其它

lintcode-medium-Pow(x, n)

2016-04-04 14:47 288 查看
Implement pow(x, n).

Notice

You don't need to care about the precision of your answer, it's acceptable if the expected answer and your answer 's difference is smaller than
1e-3
.

Example

Pow(2.1, 3) = 9.261
Pow(0, 1) = 0
Pow(1, 0) = 1


Challenge

O(logn) time

public class Solution {
/**
* @param x the base number
* @param n the power number
* @return the result
*/
public double myPow(double x, int n) {
// Write your code here

if(n == 0)
return 1;
if(n == 1)
return x;

if(n > 1){
if(n % 2 == 0){
double temp = myPow(x, n / 2);
return temp * temp;
}
else{
return myPow(x, n - 1) * x;
}
}
else{
return 1 / myPow(x, -n);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: