【LeetCode】Pow(x, n)
来源:互联网 发布:12306客户端网络有问题 编辑:程序博客网 时间:2024/05/22 16:04
题目
Implement pow(x, n).
解答
直接用递归法:
//递归法("折半"递归,不要用常规的一个个乘,效率很低)public class Solution { public double pow(double x, int n) { if(n==0) return 1; if(n==1) return x; if(n==-1) return 1/x; if(n%2==0){ double tmp=pow(x,n>>1); //减少子递归 return tmp*tmp; }else{ return pow(x,n-1)*x; } }}
若n比较小的时候,可以使用DP法,有效缓存DP的数组,性能会远超递归。当然递归也是有好处的,如果n很大,并且x不确定时,数组的空间会不够,这时就只能递归了。(此题DP法不能通过, pow(0.00001, 2147483647),应该是数组不能开太大)
//DP法:double pow(double x,int n){boolean isPositive=false;if(n==0)return 1;else if(n<0){isPositive=true;n*=-1;}double[] result=new double[n+1];result[1]=x;for(int i=2;i<=n;i++){if(i%2==0){result[i]=result[i/2]*result[i/2];}else{result[i]=result[i-1]*x;}}if(isPositive)return 1/result[n];elsereturn result[n];}
---EOF---
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)
- ORACLE 中dbms_stats的使用
- 用XML文件在Cocos2d-x中实现中文的显示
- DBMS_STATS.GATHER_TABLE_STATS详解
- 分享uboot-1.1.6移植:mini2440+K9F1G08
- LeetCode 108 Convert Sorted Array to Binary Search Tree
- 【LeetCode】Pow(x, n)
- wm_paint 消息详细解析
- 菜单的创建之CCMenuItemLabel与CCMenuItemToggle(开关按钮) 实现良种选择状态的切换
- 揭秘上海传智播客平均薪资超7k的内幕之一
- Windows程序的基本结构
- 很高兴成为CSDN.NET一名会员
- 实例讲一讲美国鞋码宽度
- sqlplus set命令
- POJ 2420 A Star not a Tree? (计算几何-费马点)