Pow(x, n)--LeetCode
来源:互联网 发布:淘宝网上有卖药的吗 编辑:程序博客网 时间:2024/05/21 12:46
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; }};
阅读全文
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)
- 枚举属性和不可枚举属性
- 爬虫学习5.1.2数据存储(无数据库)存储为CSV
- Nuxtjs vue-resource element 安装及使用
- Java Properties集合的 基本功能 方法
- 深入理解HTTP协议
- Pow(x, n)--LeetCode
- mybatis逆向工程使用(另附逆向工程项目代码)
- Linux基本操作
- 心斋-------马克奥勒流
- Android 源码分析之——Activity启动流程
- 解决url参数带”&“被截断的问题
- Cannot initialize a parameter of type 'char **' with
- Java中 ==操作符和equals方法的区别
- Java Properties 练习 计数器