[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/

0 0
原创粉丝点击