Pow(x, n):from LeetCode
来源:互联网 发布:上海交通大学 网络教育 编辑:程序博客网 时间:2024/05/22 08:18
题目大意:计算x的n次方
题目的一个解法可以用二分的思想比较普遍
题目的第二个解法可以借鉴网络传输窗口的传输阈值变化方法
第一个方法的代码如下:
class Solution {public: double pow(double x, int n) { if(n<0) { n=-n; x=1/x; } if(n==0) return 1; if(n==1) return x; double tmp; if(n%2==1) { tmp=pow(x,(n-1)/2); return tmp*tmp*x; } tmp=pow(x,n/2); tmp*tmp; }};
第二个方法的解法如下:
class Solution {public: double pow(double x, int n) { if(n==0)return 1.0000; if(n<0) { n=-n; x=1.00/x; } double tmp=1.00000; double mult=x; int dec=1; while(n) { tmp*=mult; n-=dec; if(n>=2*dec) { dec*=2; mult*=mult; }else { dec=1; mult=x; } if((tmp<0.00000001 && tmp>-0.00000001) || tmp==1.000000) return tmp; } return tmp; }};
//刚刚传错了
同时提交情况下,第二种方法时间更优。另外也是一种非迭代方法。
0 0
- Pow(x, n):from LeetCode
- 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)
- nginx 配置 vhost
- GCC 输出乱码的解决方法
- 论文类型Journal、magazin、transaction、letter等的区别
- nefu 459 矩阵连乘
- TNS-01106: "Listener using listener name %s has already been started"
- Pow(x, n):from LeetCode
- Smack Connection 的继承关系和读写接口使用说明
- 【AppCan 开发者第一期】Samlee:西北青年的移动开发梦
- Presenting view controllers on detached view controllers is discouraged
- int main(int argc,char* argv[])详解
- wifi模块调式过程
- Apache优化提高并发数量
- Android4.2.2多媒体架构MediaPlay的创建过程分析(二):解析器的创建
- Last packet sent to the server was 0 ms ago