首页 > 代码库 > [LeetCode]Power

[LeetCode]Power

周五的晚上,女朋友看爸爸去哪儿,电脑都是我的,狂刷LeetCode,做了十来题,最有印象的还是Power。题目如下:

Implement pow(xn).就是实现x的n次方。

这是一题很传统的题目了,但是之前没认真思考过。

第一个想法:比如计算pow(x, 100), 计算x,x^2,x^4,x^8,x^16,x^32,x^64.这些中间值都保存起来,再从后面开始遍历x^64*x^32*x^4;

要注意的是pow(xn)n有可能是0或者负数哦。

代码如下:

class Solution {public:    double pow(double x, int n) {        if (0==n)        {            return 1;        }        if (n < 0)        {            n = -n;            x = 1/x;        }        int current = 1;        vector<double> pd;        pd.push_back(x);        while (current<<1 < n)        {            x = x*x;            current = current<<1;            pd.push_back(x);        }        int need = n-current;        for (auto it = pd.rbegin(); need > 0 && it != pd.rend(); ++it)        {            if (current <= need)            {                x*=*it;                need-=current;            }            current=current>>1;        }        return x;    }};

然后 Memory Limit Exceeded 了:(看来中间值不能保存啊!

如果不保存中间值,总不能计算pow(x, 100), 计算x,x^2,x^4,x^8,x^16,x^32,x^64;然后再计算x,x^2,x^4,x^8,x^16,x^32;然后再计算x,x^2,x^4。

100 = 64+32+4,先做分解再算,突然意识到这不就是二进制表示吗,于是代码就简单了:

 

class Solution {public:    double pow(double x, int n) {        if (n == 0)        {            return 1;        }        if (n < 0)        {            n = -n;            x = 1/x;        }        double result = 1;        while (n > 0)        {            if (n&1==1)            {                result *= x;            }            x *= x;            n = n >> 1;        }        return result;    }};

本来觉得这个代码已经够简洁了,在Disscus看到有人用递归,自己也写了一个,除了特殊情况的判断,就一句话:

class Solution {public:    double pow(double x, int n) {        if (n == 0)        {            return 1;        }        if (n < 0)        {            n = -n;            x = 1/x;        }        return n%2 ? pow(x*x, n>>1)*x : pow(x*x, n>>1);    }};

 

[LeetCode]Power