[LintCode] Pow(x, n) 求x的n次方
2016-07-17 23:54
399 查看
Implement pow(x, n).
Notice
You don't need to care about the precision of your answer, it's acceptable if the expected answer and your answer 's difference is smaller than
Have you met this question in a real interview?
Yes
Example
LeetCode上的原题,请参见我之前的博客Pow(x, n)。
解法一:
解法二:
Notice
You don't need to care about the precision of your answer, it's acceptable if the expected answer and your answer 's difference is smaller than
1e-3.
Have you met this question in a real interview?
Yes
Example
Pow(2.1, 3) = 9.261 Pow(0, 1) = 0 Pow(1, 0) = 1
LeetCode上的原题,请参见我之前的博客Pow(x, n)。
解法一:
class Solution { public: /** * @param x the base number * @param n the power number * @return the result */ double myPow(double x, int n) { if (n == 0) return 1; double half = myPow(x, n / 2); if (n % 2 == 0) return half * half; else if (n > 0) return half * half * x; else return half * half / x; } };
解法二:
class Solution { public: /** * @param x the base number * @param n the power number * @return the result */ double myPow(double x, int n) { if (n == 0) return 0; if (n == 1) return x; if (n == -1) return 1 / x; return myPow(x, n / 2) * myPow(x, n - n / 2); } };
相关文章推荐
- Lua5.2 请求 luasocket 相关模块时的 multiple-lua-vms-detected
- 安卓内存优化之--内存泄露
- BM字符串匹配算法
- Hibernate中的事务概念及其支持的事务类型
- android为按钮事件进行监听过程
- 拓扑排序与AOE图关键路径
- FreeSWITCH dialplan APPlication
- Dubbo实战(三)多注册中心配置
- 剑指offer----连续子数组的最大和----java实现
- 硬币组合问题
- Java technical documents
- Reactor 模式的简单实现
- 删除Xcode描述文件
- javascript高级程序设计学习笔记——第三章 基本概念
- spark编程python实例
- spark编程python实例
- Java security
- (python + conda => anaconda ) + qt5 + opencv in ubuntu
- javascript运行机制之执行顺序详解
- JS运动1 (转)