您的位置:首页 > 其它

[Leetcode ??] 50 Pow(x, n)

2013-05-19 11:18 351 查看
Problem:

Implement pow(x, n).

Analysis:

Notice n may be negative numbers.

Simply use for loop to implement is okay when n is small. When n is large enough, it may cause Time Limit Exceeded error. In this way, the time complexity is O(n).

There's a recursive implementation method can reduce the complexity to O(logn), which is faster when n is big.

Code:

public class Solution {
public double pow(double x, int n) {
// Start typing your Java solution below
// DO NOT write main() function
if (n == 0) return 1;

double res = 1;
boolean isPos = (n>=0)?true:false;

n = isPos?n:-n;

if (n%2 == 0) {
res = pow(x, n/2);
res *= res;
} else {
res = pow(x, (n-1)/2);
res *= x * res;
}

return isPos?res:1/res;
}
}


View Code

Attention:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: