[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:
View Code
Attention:
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:
相关文章推荐
- 【LeetCode】LeetCode50 Pow(x, n)
- 【LeetCode】50_Pow(x, n)
- LeetCode(50) Pow(x,n)
- [Leetcode 50, Medium] Pow(x, n)
- 【leetcode】【50】Pow(x, n)
- LeetCode_50---Pow(x, n)
- LeetCode-50-Pow(x, n)( 二分法)-Medium
- LeetCode50 Pow(x, n) 解题报告
- 【小熊刷题】power of two, pow(x, n) <Leetcode 231, 50 Java>
- leetcode_question_50 Pow(x, n)
- leetcode-50 Pow(x, n) 剑指Offer题11 数值的整数次方
- leetcode50-Pow(x, n)(实现浮点数的幂运算)
- leetcode 50:Pow(x, n)
- leetcode || 50、Pow(x, n)
- LeetCode50——Pow(x,n)
- LeetCode(50)Pow
- LeetCode 50 Pow(x, n)
- [LeetCode]50 Pow(x, n)
- leetcode50_Pow(x, n)
- Leetcode 50 - Pow(x, n)