[leetcode]Pow(x, n)
来源:互联网 发布:禁止淘宝客是什么意思 编辑:程序博客网 时间:2024/05/27 01:33
题目描述如下:
Implement pow(x, n),实现浮点类型的幂运算。
看到这个题目感觉很奇怪于是尝试用自带的函数去试一下时间条件。
public class Solution { public double myPow(double x, int n) { if(n == 0) return 1.0; if(n < 0) return 1.0 / Math.pow(x,-n); return Math.pow(x,n); }}
这样居然就过了…medium难度的题目。但是时间理所当然用了很久。
稍微在这个基础上改成了递归,减少Math.pow函数的执行,代码如下:
public class Solution { public double myPow(double x, int n) { if(n == 0) return 1.0; if(n < 0) return 1.0 / Math.pow(x,-n); return x * Math.pow(x,n - 1); }}
时间一下子从2ms减少到1ms。
感觉不够,于是去了解了其他的几种解法。
1、二分法
考虑到n个x相乘式子的对称关系,可以对上述方法进行改进,从而得到一种时间复杂度为O(logn)的方法,递归关系可以表示为pow(x,n) = pow(x,n/2)*pow(x,n-n/2)
public class Solution { public double power(double x, int n){ if(n == 0) return 1; double v = power(x, n / 2); if(n % 2 == 0) return v * v; else return v * v * x; } public double myPow(double x, int n) { if(n < 0) return 1.0 / power(x, -n); else return power(x, n); }}
2、扫描n二进制表示形式里不同位置上的1,来计算x的幂次
转自:http://blog.csdn.net/fengbingyang/article/details/12236121
方法描述:Consider the binary representation of n. For example, if it is “10001011”, then x^n = x^(1+2+8+128) = x^1 * x^2 * x^8 * x^128. Thus, we don’t want to loop n times to calculate x^n. To speed up, we loop through each bit, if the i-th bit is 1, then we add x^(1 << i) to the result. Since (1 << i) is a power of 2, x^(1<<(i+1)) = square(x^(1<
double my_pow(double x, int n){ if(n==0) return 1.0; if(n<0) return 1.0 / pow(x,-n); double ans = 1.0 ; for(; n>0; x *= x, n>>=1) { if(n&1>0) ans *= x; } return ans;}
像这样的题目,还是需要多几种解决方案才对得起这个难度…
题目链接:https://leetcode.com/problems/powx-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)
- LeetCode | Pow(x, n)
- Pow(x, n) -leetcode
- 【leetcode】Pow(x, n)
- 【Leetcode】Pow(x, n)
- LeetCode Pow(x, n)
- Leetcode: Pow(x, n)
- 日拱一卒
- 阿里云ubuntu集成nginx+tomcat7
- Hirbernate实现对数据的增删该查
- 深度学习系列(二):从神经网络到深度学习
- 趣学Python-教孩子学编程--第八章
- [leetcode]Pow(x, n)
- 计算机的引导过程
- ARM处理器
- c++ iterator(迭代器)分类及其使用
- ARC和非ARC(-fobjc-arc和-fno-objc-arc)
- OpenJudge_P7834 分成互质组
- C#与C++的混合编程 之一 方法介绍
- 以指针方式访问数组几种不同形式输出语句解析
- 内核引导过程