[LeetCode] Pow(x, n)
来源:互联网 发布:淘宝卖自家产大米 编辑:程序博客网 时间:2024/06/03 23:48
Pow(x, n)
Implement pow(x, n).
解题思路:
这里n是整数,注意可能是负数,因此需要先将其转化成正数。若直接用循环的方法做,会产生超时错误。我们可以这么做。比如求2^6,我们需要求2^(2*3)=4^3=4*4^2,这样时间复杂度为O(logn)。
注意几个特殊的情况,当n==1时,返回x本身,当n==0时,返回1,当n为偶数时,返回myPow(x*x, n/2),当n为奇数时,返回x*myPow(x*x, n/2)
class Solution {public: double myPow(double x, int n) { if(n<0){ n=-n; x=1/x; } if(n==1){ return x; } if(n==0){ return 1; } double temp=1; if(n%2==1){ temp=x; } return temp * myPow(x*x, n/2); }};
update in 2015.05.27
后来分析了一下,上述代码中,n==1的分支其实可以不必的。因此,代码就变成了:
class Solution {public: double myPow(double x, int n) { if(n<0){ n=-n; x=1/x; } if(n==0){ return 1; } double temp=1; if(n%2==1){ temp=x; } return temp * myPow(x*x, n/2); }};
0 0
- LeetCode: Pow(x, n)
- LeetCode Pow(x,n)
- [Leetcode] Pow(x, n)
- LeetCode: Pow(x, n)
- Leetcode: Pow(x,n)
- [LeetCode] Pow(x, n)
- [Leetcode] Pow(x,n)
- 【leetcode】Pow(x, n)
- [LeetCode]Pow(x, n)
- [leetcode]Pow(x, n)
- LeetCode-Pow(x, n)
- LeetCode - Pow(x, n)
- LeetCode | Pow(x, n)
- Pow(x, n) -leetcode
- 【leetcode】Pow(x, n)
- 【Leetcode】Pow(x, n)
- LeetCode Pow(x, n)
- Leetcode: Pow(x, n)
- Codeforces Round #254 (Div. 2) E. DZY Loves Colors(线段树 成段更新)
- C ++ 11 New Feature Notes
- 人生第一面——腾讯
- CMD 常用命令
- 9、图
- [LeetCode] Pow(x, n)
- ImageView圆角
- USACO3.3--Shopping Offers
- 测试文章
- Java学习日记之类和对象继续深入:继承
- 对象归档
- 苹果最重要的男人,如何实现职业的三次跳跃?
- eclipse我用到的技巧收集
- Qt学习记录3——登陆窗口的实现