[LeetCode 050] Pow(x, n)
2016-02-15 09:16
225 查看
Pow(x, n)
n == 0时,结果为1
n > 0时,结果是
x ^ n
否则,为上述结果的倒数
if n是odd\({x}^{n} = {x}^{\frac{n}{2}}\times{x}^{\frac{n}{2}}\times{x} \)
if n是even\({x}^{n} = {x}^{\frac{n}{2}}\times{x}^{\frac{n}{2}} \)
Implementation
Recursive
public class Solution { public double myPow(double x, int n) { if (n < 0) { x = 1 / x; } return pow(x, n); } public double pow(double x, int n) { if (n == 0) return 1; double factor = pow(x, n / 2); factor *= factor; if (Math.abs(n % 2) == 1) factor *= x; return factor; } }
Iterative
从下到上两两相乘,多余的一个乘到结果中(n代表这一层有几个数)public class Solution { public double myPow(double x, int n) { if (n < 0) { x = 1 / x; } double result = 1; while (n != 0) { if (Math.abs(n % 2) == 1) { result = result * x; } x = x * x; n = n / 2; } return result; } }
相关文章推荐
- s7-1200PLC的PID调节问题
- 读jquery.cookie.js源码学到的几个技巧
- 用Telnet发送HTTP请求
- 单元测试NUnit教程
- Android 查看pdf文档——PDFView
- 中产的焦虑
- bootstrap分页
- 登录名称
- MySQL集群搭建详解
- try和finally执行顺序
- 反编译与混淆
- FineReport实现根据点击次数奇偶性排序的方法
- Win7/Win8系统IE浏览器下载文件没反应的7种解决方法
- linux下ffmpeg安装
- 投资自己
- PHP扩展迁移为PHP7扩展兼容性问题记录
- RxJava中多线程机制
- Eclipse安装插件不显示
- Bitmap.Config ARGB_8888
- 大型网站的架构演变