Pow(x, n)--LeetCode
2017-10-15 15:19
281 查看
1.题目
Pow(x, n)Implement pow(x, n).
2.题意
实现pow(x, n)3.分析
1)递归版求x的n次方,for循环让x乘以自己n次,会因超时无法通过
用递归来折半计算,每次把n缩小一半,这样n最终会缩小到等于0
任何数的0次方都为1
这时再往回乘
如果n是偶数,直接把上次递归得到的值平方后返回
如果n是奇数,则还需要乘以x
注意对于n是负数的情况,可以先用相反数计算出结果再取其倒数即可
2)迭代版
迭代解法,i的初始值为n,若i为2的倍数,则x乘以自己
否则res乘以x
i每次循环缩小一半,直到为0停止循环
最后注意不要遗漏n的正负,如果为负,返回其倒数
n在最后在判断符号,所以i!=0不能写成i>0
if(i%2!=0)不要写成if(n%2!=0)
return n>=0?res:1.0/res;一定不要写成return n>=0?res:-res;
4.代码
1)递归版class Solution { public: double myPow(double x, int n) { if(n < 0) return 1.0 / myPower(x, -n); else return myPower(x, n); } private: double myPower(double x, int n) { if(n == 0) return 1.0; double half = myPower(x, n / 2); if(n % 2 == 0) return half * half; else return x * half *half; } };
2)迭代版
class Solution { public: double myPow(double x, int n) { double res = 1.0; for(int i = n; i != 0; i /= 2) { if(i % 2 != 0) res *= x; x *= x; } return n >= 0 ? res : 1.0 / res; } };
相关文章推荐
- Leetcode: Pow(x,n)
- [LeetCode] Pow(x, n)
- [leetcode 50]pow(x,n)
- LeetCode | Pow(x, n)
- leetcode - Pow(x, n)
- [java][leetcode 372]Super Pow
- LeetCode 50:Pow(x, n)
- 【leetcode】Pow(x,n)
- [LeetCode]Pow(x, n)
- [LeetCode-Algorithms-50] "Pow(x, n)" (2017.10.25-WEEK8)
- leetcode第一刷_Pow(x, n)
- LeetCode No.50 Pow(x, n)
- [leetcode]Pow(x, n)
- Leetcode NO.50 Pow(x, n)
- LeetCode-Pow
- leetcode-pow(x,n)
- Leetcode -- Pow(x, n)
- 372. Super Pow(LeetCode)
- LeetCode - Pow
- LeetCode - Pow(x, n)