LeetCode-50. Pow(x, n)
来源:互联网 发布:个体户办淘宝企业店铺 编辑:程序博客网 时间:2024/05/22 05:18
问题描述
实现自己的次幂函数,返回x^n的值。
解题思路
解题思路参考自这篇博客
1. 利用递归
依次递归求解double res=Pow(x,n/2),然后返回res*res或者res*res*n(前者n为偶数,后者为奇数);而不是直接返回Pow(x,n/2)*Pow(x,n/2)或者Pow(x,n/2)*Pow(x,n/2)*x。另外,需要考虑边界的问题,如果x=0,x=1,x<0,以及x=Integer.MIN_VALUE。
2. 利用动态规划
我们可以尝试将x^n分解,以x^13为例,13的二进制数为1101,上式可以分解为
代码
递归
public class Solution { public double myPow(double x, int n) { if(n==0) return 1; if(n==1) return x; int tem=n/2; if(n<0){ tem=-tem; x=1/x; } double res=myPow(x,tem); if(n%2==0) return res*res; return res*res*x; }}
动态规划
public class Solution { public double myPow(double x, int n) { if(n==0) return 1; if(n==1) return x; int m=(n<0?-n-1:n);//处理n为负数的情况 double result=1; for(double p=x;m>0;m/=2){ if((m & 1)!=0) result*=p; p*=p; } if(n<0){ return 1/result/x; } return result; }}
阅读全文
0 0
- [LeetCode]50.Pow(x, n)
- LeetCode --- 50. Pow(x, n)
- [Leetcode] 50. Pow(x, n)
- [leetcode] 50.Pow(x, n)
- LeetCode 50. Pow(x, n)
- 50. Pow(x, n) LeetCode
- [leetcode] 50. Pow(x, n)
- Leetcode 50. Pow(x, n)
- [LeetCode]50. Pow(x, n)
- LeetCode *** 50. Pow(x, n)
- LeetCode 50. Pow(x, n)
- LeetCode 50. Pow(x, n)
- 【LeetCode】50. Pow(x, n)
- [leetcode]50. Pow(x, n)
- LeetCode-50.Pow(x, n)
- LeetCode - 50. Pow(x, n)
- [LeetCode] 50. Pow(x, n)
- LeetCode 50. Pow(x, n)
- 使用nginx+tomcate做二级域名
- JAVA 的反射基础
- 喜欢的博客、网站
- IOS开发疑难杂症排查-常用hook方法
- java中ArrayList和LinkedList的区别
- LeetCode-50. Pow(x, n)
- Android实现异步请求
- testNG测试报告美化
- 时间复杂度和空间复杂度详解
- C#180课的主要内容
- java学习 jstl标签中remove标签的使用
- 算法设计与结构基础作业第十八周
- Linux--进程间通信总结
- IOS APP启动优化路线图