LeetCode之Pow(x, n)
2015-09-02 17:13
232 查看
/*直接模仿数学中的乘幂算法。*/ class Solution { public: double myPow(double x, int n) { if(n == 0) return 1.0; else if(fabs(x) < 1e-10) return 0.0; else{ if(n > 0){ if(x > 0.0) return myPowPositive(x, n); else{ if((n & 1) == 0) return myPowPositive(-x, n);//n为偶数 else return -myPowPositive(-x, n);//n为奇数 } } else{ if(x > 0.0) return 1.0 / myPowPositive(x, -n); else{ if((n & 1) == 0) return 1.0 / myPowPositive(-x, -n); else return -1.0 / myPowPositive(-x, -n); } } } } double myPowPositive(double x, int n){ double res(1.0); double eps = 1e-10; for(int i = 0; i < n; ++i){ if(fabs(res * x - res) < eps) return res; res *= x; } return res; } }; /*采用二分法加速。*/ class Solution { public: double myPow(double x, int n) { if(n < 0) return 1.0 / myPow_sub(x, -n); else return myPow_sub(x, n); } double myPow_sub(double x, int n){ if(n == 0) return 1.0; double tmp = myPow_sub(x, n/2); if((n & 1) == 0) return tmp * tmp; else return tmp * tmp * x; } };
相关文章推荐
- mysql-concat扩展函数
- Android OpenGL es GPUImage convert YUV to RGB
- mysql root 忘记密码
- BrowserSync(省时的浏览器同步测试工具)
- Java内存泄露的理解与解决
- bzoj3555
- Android中修改源码实现AutoCompeteTextView控件的模糊匹配
- Unity3D如何有效地组织代码?
- 个性化WinPE封装方法《第三讲---- 配置开始菜单及桌面环境》
- C语言调用 Java(Linux)
- GIT的使用
- ios软件开发 获取手势点击视图的tag
- poj3067 Japan (树状数组)
- java中String类型的最大长度
- 大型网站架构模式
- [ActionScript 3.0] AS3 绘制立方体
- java 截取汉字
- 个性化WinPE封装方法《第二讲----添加应用程序》
- Android 最火的快速开发框架XUtils
- 给超链接加onclick事件